使用pd.np.where出错的Python Dataframe条件If语句
我有以下数据帧:使用pd.np.where出错的Python Dataframe条件If语句,python,pandas,if-statement,conditional-statements,Python,Pandas,If Statement,Conditional Statements,我有以下数据帧: count country year age_group gender type 7 Albania 2006 014 f ep 1 Albania 2007 014 f ep 3 Albania 2008 014 f ep 2 Albania 2009 014 f ep 2
count country year age_group gender type
7 Albania 2006 014 f ep
1 Albania 2007 014 f ep
3 Albania 2008 014 f ep
2 Albania 2009 014 f ep
2 Albania 2010 014 f ep
我试图对“性别”一栏进行调整,使“f”变成“女性”,m和男性也一样
我尝试了以下代码:
who3['gender'] = pd.np.where(who3['gender'] == 'f', "female")
但它给了我一个错误:
现在,当我尝试此代码时:
who3['gender'] = pd.np.where(who3['gender'] == 'f', "female",
pd.np.where(who3['gender'] == 'm', "male"))
我得到以下错误信息:
我做错了什么?
np。其中
需要条件作为第一个参数,如果条件满足,则需要期望输出,如果条件不满足,则需要第三个参数作为输出,请尝试以下操作:
who3['gender'] = np.where(who3['gender'] == 'f', "female", 'male')
另一种解决方案是使用replace
方法:
who3['gender'] = who3['gender'].replace({'f': 'female', 'm': 'male'})
np.其中
需要条件作为第一个参数,如果条件满足,则需要期望输出,如果条件不满足,则需要第三个参数作为输出,请尝试以下操作:
who3['gender'] = np.where(who3['gender'] == 'f', "female", 'male')
另一种解决方案是使用replace
方法:
who3['gender'] = who3['gender'].replace({'f': 'female', 'm': 'male'})
您还可以使用
.replace()
:
印刷品:
count country year age_group gender type
0 7 Albania 2006 14 female ep
1 1 Albania 2007 14 female ep
2 3 Albania 2008 14 female ep
3 2 Albania 2009 14 female ep
4 2 Albania 2010 14 female ep
您还可以使用
.replace()
:
印刷品:
count country year age_group gender type
0 7 Albania 2006 14 female ep
1 1 Albania 2007 14 female ep
2 3 Albania 2008 14 female ep
3 2 Albania 2009 14 female ep
4 2 Albania 2010 14 female ep
pd是pd.np.where的一部分吗?是的。因为
np。其中
是一个numpy函数,而不是一个panda函数。我还为您的问题添加了另一个解决方案。pd.np的pd部分是否不必要?是的。因为np。其中
是一个numpy函数,而不是一个panda函数。我还为你的问题添加了另一个解决方案。