python - Consecutive next value into new column pandas dataframe -
i have dataframe
id value v1 100 v1 200 v1 300 v1 400 v2 500 v2 600 v2 700 v3 800 v3 900
i looking transform dataframe new dataframe df2:
id val1 val2 v1 100 200 v1 200 300 v1 300 400 v1 400 100 v2 500 600 v2 600 700 v2 700 500 v3 800 900 v3 900 800
i.e shifting next consecutive value in next column , kind of grouping id's,
i tried using df.shift() , not working.
is there alternative this?
we want use np.roll
accomplish task within groups. using transform
, bypass getting hung within group index.
df.groupby('id').value.transform(np.roll, shift=-1) 0 200 1 300 2 400 3 100 4 600 5 700 6 500 7 900 8 800 name: value, dtype: int64
we can add new column copy of df
assign
df.assign(val2=df.groupby('id').value.transform(np.roll, shift=-1)) id value val2 0 v1 100 200 1 v1 200 300 2 v1 300 400 3 v1 400 100 4 v2 500 600 5 v2 600 700 6 v2 700 500 7 v3 800 900 8 v3 900 800
or add new column directly df
in place
df['val2'] = df.groupby('id').value.transform(np.roll, shift=-1) df id value val2 0 v1 100 200 1 v1 200 300 2 v1 300 400 3 v1 400 100 4 v2 500 600 5 v2 600 700 6 v2 700 500 7 v3 800 900 8 v3 900 800
Comments
Post a Comment