Reputation: 17
I have a dataframe:
df =
col1 | Aciton1 |
---|---|
1 | A |
2 | B |
3 | C |
1 | C |
I want to edit df, such that when the value of col1 is bigger than 1 , take the value from Action1.
So I will get:
col1 | Aciton1 | Previous_Aciton |
---|---|---|
1 | A | Initial Action |
2 | B | A |
3 | C | B |
1 | C | Initial Action |
Upvotes: 1
Views: 866
Reputation: 4543
Use:
df = pd.DataFrame({'col1': [1,2,3], 'act1': ['A', 'B', 'C'], 'Previsou_Aciton':['G', 'H', 'I']})
temp = df[df['col1']>1].index
df['Previsou_Aciton'].loc[temp]=df.loc[[x-1 for x in temp]]['act1'].values
input df:
the result:
Upvotes: 0
Reputation: 862651
If there are no negative and 0
values and each group starting by 1
is possible use DataFrameGroupBy.shift
:
df['Previsou_Aciton'] = df.groupby(df['col1'].eq(1).cumsum())['Aciton1'].shift(fill_value='Initail Action')
print (df)
col1 Aciton1 Previsou_Aciton
0 1 A Initail Action
1 2 B A
2 3 C B
3 1 C Initail Action
Upvotes: 1