【发布时间】:2019-07-17 05:55:31
【问题描述】:
我正在尝试逐行使用条件,如果为真,则逐行更改我的数据框中的变量。
这里是一些示例数据:
import pandas as pd
data = {'grade' : [1,2,3], 'new_grade': [np.nan, np.nan, np.nan], 'pred1': ['yes','no-x','no'], 'pred2': ['yes-x','yes-x', 'yes'], 'pred3': ['yes','no-x','yes']}
df = pd.DataFrame(数据) 打印(df)
grade new_grade pred1 pred2 pred3
0 1 NaN yes yes-x yes
1 2 NaN no-x yes-x no-x
2 3 NaN no yes yes
在示例中,如果 pred1、pred2 或 pred3 中的任何一个中都没有“x”,我希望“new_grade”保持不变。如果 pred1、pred2 或 pred3 中的每个变量都有一个“x”,我想从“grade”中减去 1,并将其保存为“new_grade”。
我试过了,但它没有给我想要的结果:
df['new_grade'] = np.where('x' not in str(df[['pred1', 'pred2', 'pred3',]]), df['grade'], df['grade']-1)
这是所需的输出:
grade new_grade pred1 pred2 pred3
0 1 1 yes yes-x yes
1 2 1 no-x yes-x no-x
2 3 3 no yes yes
不确定是否需要使用 iterrows() 进行 for 循环?
任何帮助将不胜感激。
谢谢!
【问题讨论】:
-
对不起,我搞砸了所需的输出。现在是正确的
标签: python pandas conditional-statements