检查各个列中是否存在字符串。如果存在,请在熊猫中更改另一个变量

时间:2019-07-16 21:21:27

标签: python pandas conditional-statements

我试图逐行使用条件,如果为true,则逐行更改数据框中的变量。

以下是一些示例数据:

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循环?

任何帮助将不胜感激。

谢谢!

3 个答案:

答案 0 :(得分:1)

对于您而言,我们可以使用contains

df['new_grade']=df.grade-df.loc[:,'pred1':].apply(lambda x : x.str.contains('-x')).all(1)
df
Out[591]: 
   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

答案 1 :(得分:1)

我们可以使用df.filter获取所有pred列,并检查它们是否包含x。然后使用np.wheregrade有条件地从.sub中减去1:

m = df.filter(like='pred').apply(lambda x: x.str.contains('x'), axis=1).all(axis=1)

df['new_grade'] = np.where(m, df['grade'].sub(1), df['grade'])

输出

   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

输出为NaN

   grade  new_grade pred1  pred2 pred3  pred4
0      1          1   yes  yes-x   yes    NaN
1      2          1  no-x  yes-x  no-x    NaN
2      3          3    no    yes   yes    NaN

答案 2 :(得分:1)

尝试:

cond1 = df.pred1.str.endswith('x')
cond2 =  df.pred2.str.endswith('x')
cond3 = df.pred3.str.endswith('x')
df['new_grad'] = df['grade'].where(~(cond1 & cond2 & cond3), df['grade'] - 1)