[英]Change the values of a dataframe, based on condition
数据框内的案例陈述,我在这里做错了什么?
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 if x =='Closed with non-monetary relief' ^ SyntaxError: 语法无效
我认为这里最好按字典使用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
s 列:
df1['Response'] = df1['Response'].map(d).fillna(-1).astype(int)
试试这个格式,它应该可以工作:
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 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.