Reputation: 122
I have a data frame that has two columns:
A B
0 0
0 1
0 0
0 0
0 0
0 1
I want to have some code that checks the B column and when a 1 is found, the values of column A from that INDEX on changes to 1 like this;
A B
0 0
1 1
1 0
1 0
1 0
1 1
My code is like this but it is not what I want:
df['A']= np.where(df['B'] == 1,df['A'], '1')
Upvotes: 3
Views: 51
Reputation: 323226
Let us try cummax
df['A']=df.B.cummax()
df
Out[302]:
A B
0 0 0
1 1 1
2 1 0
3 1 0
4 1 0
5 1 1
Upvotes: 2
Reputation: 61910
You could do:
df.loc[df['B'].idxmax():, 'A'] = 1
print(df)
Output
A B
0 0 0
1 1 1
2 1 0
3 1 0
4 1 0
5 1 1
If you want to use np.where, do:
df['A'] = np.where(df.index < df['B'].idxmax(), df['A'], 1)
print(df)
If the column B
can have other values besides 0s and 1s, do:
df['A'] = np.where(df.index < df['B'].eq(1).idxmax(), df['A'], 1)
Upvotes: 5