I have the following dataframe (created for an example):
JavaScript
x
7
1
In [2]: df
2
Out[2]:
3
A B
4
0 1 2
5
1 1 3
6
2 4 6
7
Assuming that this is a long dataframe, whenever there is a value of 2 in row B, I need to replace that value with the value that is two cells below that.
I tried:
JavaScript
1
4
1
for val in df['B']:
2
if val == 2:
3
df['B'] = df.B.shift(-2)
4
But I get:
JavaScript
1
5
1
A B
2
0 1 6.0
3
1 1 NaN
4
2 4 NaN
5
And I need:
JavaScript
1
6
1
Out[2]:
2
A B
3
0 1 6
4
1 1 3
5
2 4 6
6
Does anyone have suggestions for leaving rows that do not equal ‘2’ unchanged?
Advertisement
Answer
Then we just need to assign it with shift
JavaScript
1
8
1
df.loc[df['B'].eq(2),'B'] = df.B.shift(-2)
2
df
3
Out[458]:
4
A B
5
0 1 6.0
6
1 1 3.0
7
2 4 6.0
8