当A列满足以下特定条件时,我想复制B列中的单元格值,并创建一个新的C列:
1.“前进”切换到“停止”或“后退”时
1.“后退”切换到“停止”或“前进”时
例如,
| A类|B|C级|
| - ------|- ------|- ------|
| 停|无|无|
| 前进|十个|无|
| 前进|二十个|无|
| 前进|三十|三十|
| 向后|十个|无|
| 向后|二十五|无|
| 向后|四十|四十|
| 停|无|无|
| 停|无|无|
| 向后|五个|无|
| 向后|十个|十个|
| 前进|二十个|无|
| 前进|三十|三十|
| 停|无|无|
我试着按照代码,但它不工作,列C存储什么.
for idx, row in df.iterrows():
if idx <= 1:
continue
A1 = row['A']
A0 = df.iloc[idx + 1]['A']
B1 = row['B']
def C(df):
if A1 == "Forward" and A0 == "Stop":
return B1
if A1 == "Backward" and A0 == "Stop":
return B1
elif A1 == "Forward" and A0 == "Backward":
return B1
elif A1 == "Backward" and A0 == "Forward":
return B1
df['C'] = df.apply(C, axis = 1)
我也试过这个,但是它不起作用
for idx, row in df.iterrows():
if idx <= 1:
continue
A1 = df.iloc[idx - 1]['A']
A0 = row['A']
B1 = df.iloc[idx - 1]['B']
def C(df):
if A1 == "Forward" and A0 == "Stop":
return B1
if A1 == "Backward" and A0 == "Stop":
return B1
elif A1 == "Forward" and A0 == "Backward":
return B1
elif A1 == "Backward" and A0 == "Forward":
return B1
df['C'] = df.apply(C, axis = 1)
1条答案
按热度按时间ioekq8ef1#
使用布尔掩码:
备选方案:
输出:
中间体: