根据条件更改数据框的值

时间:2019-11-29 07:02:17

标签: python pandas

数据框内的case语句,我在这里做什么错了?

df1['Response'] = [4 if x =='Closed with monetary relief' 
               3 if x =='Closed with non-monetary relief'
               2 if x =='Closed with explanation' 
               1 if x =='Closed' 
               0 if x =='Untimely response' for x in df1['Response']] 

我看到的错误:

  

3,如果x =='通过非货币救济关闭'       ^ SyntaxError:语法无效

2 个答案:

答案 0 :(得分:1)

我认为最好按字典使用Series.map

d = {'Closed with monetary relief' : 4,
     'Closed with non-monetary relief':3.
     'Closed with explanation':2,
     'Closed':1,
     'Untimely response':0}

df1['Response'] = df1['Response'].map(d)

如果某些不匹配的值丢失了值,则可以将其替换为原始值:

df1['Response'] = df1['Response'].map(d).fillna(df1['Response'])

或其他一些值,例如-1,然后还将值转换为整数,因为至少有一个NaN创建了float列:

df1['Response'] = df1['Response'].map(d).fillna(-1).astype(int)

答案 1 :(得分:1)

尝试这种格式,它应该可以工作:

df1.Response.apply(lambda x: 4 if x =='Closed with monetary relief' else
               3 if x =='Closed with non-monetary relief' else
               2 if x =='Closed with explanation' else
               1 if x =='Closed' else
               0 if x =='Untimely response' else None )