数据框内的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:语法无效
答案 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 )