[英]How can I change values in the column contating Nan and certain values of Dataframe in Python?
I have a problem about changing certain values (Non-Nan Values) in a MONTH column of the dataframe.我在更改 dataframe 的 MONTH 列中的某些值(非南值)时遇到问题。 The month column contains the deduction month name of a year except for NaN values.
月份列包含一年的扣除月份名称,但 NaN 值除外。 I try to redefine the full name of each one in a MONTH column but I couldn't do that.
我尝试在 MONTH 列中重新定义每个人的全名,但我做不到。
Here is my code showing unique values of the Month column这是我的代码,显示了 Month 列的唯一值
df[df["MONTH"].notnull()]["MONTH"].unique()
array(['Aug', 'Mar', 'Oct', 'Nov', 'May', 'Sep', 'Apr', 'Jul', 'Jun',
'Jan', 'Feb', 'Dec'], dtype=object)
Here is my code which is shown below.这是我的代码,如下所示。
df.loc[df[df["MONTH"].notnull()]["MONTH"] == 'Aug', 'MONTH'] = "August"
df.loc[df[df["MONTH"].notnull()]["MONTH"] == 'Mar', 'MONTH'] = "March"
df.loc[df[df["MONTH"].notnull()]["MONTH"] == 'Oct', 'MONTH'] = "October"
df.loc[df[df["MONTH"].notnull()]["MONTH"] == 'Nov', 'MONTH'] = "November"
df.loc[df[df["MONTH"].notnull()]["MONTH"] == 'May', 'MONTH'] = "May"
df.loc[df[df["MONTH"].notnull()]["MONTH"] == 'Sep', 'MONTH'] = "September"
df.loc[df[df["MONTH"].notnull()]["MONTH"] == 'Apr', 'MONTH'] = "April"
df.loc[df[df["MONTH"].notnull()]["MONTH"] == 'Jul', 'MONTH'] = "July"
df.loc[df[df["MONTH"].notnull()]["MONTH"] == 'Jun', 'MONTH'] = "June"
df.loc[df[df["MONTH"].notnull()]["MONTH"] == 'Jan', 'MONTH'] = "January"
df.loc[df[df["MONTH"].notnull()]["MONTH"] == 'Feb', 'MONTH'] = "February"
df.loc[df[df["MONTH"].notnull()]["MONTH"] == 'Dec', 'MONTH'] = "December"
Here is the error which is shown below.这是如下所示的错误。
TypeError: 'Series' objects are mutable, thus they cannot be hashed
How can I fix it?我该如何解决?
Please let me suggest a perhaps better way of dealing with the issue (the possible problem in your code is addressed below).请让我提出一种可能更好的方法来处理该问题(您的代码中可能存在的问题在下面得到解决)。 Simply use pandas
replace()
in a single line.只需在一行中使用 pandas
replace()
。 It will be a lot more efficient, as your code is calling and slicing the dataframe object 12 times instead of once.:这会更有效率,因为您的代码正在调用和切片 dataframe object 12 次而不是一次。:
replacements = {'Jan':'January','Feb':'Febraury','Mar':'March','Apr':'April','May':'May','Jun':'June','Jul':'July','Aug':'August','Sep':'September','Oct':'October','Nov':'Novemeber','Dec':'December'}
df['MONTH'] = df['MONTH'].replace(replacements)
With regards to your error, I think you can add .index
in order to help you get the first argument of loc
:关于您的错误,我认为您可以添加
.index
以帮助您获得loc
的第一个参数:
df.loc[(df[df["MONTH"].notnull()]["MONTH"] == 'Aug').index, 'MONTH'] = "August"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.