2 回答
TA贡献2041条经验 获得超4个赞
您可以shift与numpy.where
import numpy as np
b1 = df["B"].shift(-1)
df["C"] = np.where((df["B"]=="X") & (b1!="X"), "str" , df["C"])
输出:
A B C
0 1 X 1
1 1 X 1
2 1 X str
3 1 D 1
4 1 A 1
5 1 A 1
6 1 X str
7 1 D 1
TA贡献1796条经验 获得超4个赞
mask = (df['B'] == 'X').astype(int)
mask = mask - mask.shift(-1)
df.loc[mask == 1, 'C'] = 'str'
df
Out[44]:
A B C
0 1 X 1
1 1 X 1
2 1 X str
3 1 D 1
4 1 A 1
5 1 A 1
6 1 X str
7 1 D 1
解释:
df = pd.DataFrame({
'A' : [1,1,1,1,1,1,1,1],
'B' : ['X','X','X','D','A','A','X','D'],
'C' : [1,1,1,1,1,1,1,1],
})
df
Out[35]:
A B C
0 1 X 1
1 1 X 1
2 1 X 1
3 1 D 1
4 1 A 1
5 1 A 1
6 1 X 1
7 1 D 1
现在你可以有一个面具,其中df['B']=='X':
df['mask'] = (df['B'] == 'X').astype(int)
df
Out[37]:
A B C mask
0 1 X 1 1
1 1 X 1 1
2 1 X 1 1
3 1 D 1 0
4 1 A 1 0
5 1 A 1 0
6 1 X 1 1
7 1 D 1 0
为了找到要替换的行,您可以执行以下操作:
df['mask'] = df['mask'] - df['mask'].shift(-1)
df
Out[39]:
A B C mask
0 1 X 1 0.0
1 1 X 1 0.0
2 1 X 1 1.0
3 1 D 1 0.0
4 1 A 1 0.0
5 1 A 1 -1.0
6 1 X 1 1.0
7 1 D 1 NaN
最后:
df.loc[df['mask'] == 1, 'C'] = 'str'
df
Out[41]:
A B C mask
0 1 X 1 0.0
1 1 X 1 0.0
2 1 X str 1.0
3 1 D 1 0.0
4 1 A 1 0.0
5 1 A 1 -1.0
6 1 X str 1.0
7 1 D 1 NaN
添加回答
举报