当值等于 列
中的特定值时,我想在 pandas
df
中移动 rows
>。对于下面的 df
,当 A == x 中的值时,我试图将
。Column B
中的值移动到 Column A
import pandas as pd
df = pd.DataFrame({
'A' : [1,'x','x','x',5],
'B' : ['x',2,3,4,'x'],
})
这是我的尝试:
df = df.loc[df.A.shift(-1) == df.A.shift(1), 'x'] = df.A.shift(1)
预期输出:
A B
0 1 x
1 2
2 3
3 4
4 5 x
最佳答案
您可以使用:
m = df.A.eq('x')
df[m]=df[m].shift(-1,axis=1)
print(df)
A B
0 1 x
1 2 NaN
2 3 NaN
3 4 NaN
4 5 x
关于python - 当等于特定值时移动列中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55036882/