Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/clojure/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 根据条件更改数据帧的值_Python_Pandas - Fatal编程技术网

Python 根据条件更改数据帧的值

Python 根据条件更改数据帧的值,python,pandas,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 =='U

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

我认为以下是字典的最佳用法:

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 )

请分享您的整个计划,或至少分享相关领域。可能还有其他单一的选择会使事情复杂化。无论如何,这是不正确的语法,不管它是否是惯用的Pandas。这种方法对于大型数据帧来说效率很低,最好使用Pandas内置函数,如@jezrael suggestswwhy是
astype(int)
required?@alexander cécile-yop,因为至少有一个NaN将值转换为浮点值,太有必要了。啊,那是真的,南是个浮子!我让你保持警觉;)我不想让你觉得太舒服:p尽管我不知道最后一个问题是不是个好问题。我可能心烦意乱,没有想清楚。