【问题标题】:Python Dataframe Conditional If Statement Using pd.np.where Erroring OutPython Dataframe 条件 If 语句使用 pd.np.where 出错
【发布时间】:2021-06-26 20:26:18
【问题描述】:

我有以下数据框:

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"))

我收到以下错误:

我做错了什么?

【问题讨论】:

    标签: python pandas if-statement conditional-statements


    【解决方案1】:

    你也可以使用.replace():

    df["gender"] = df["gender"].replace({"f": "female", "m": "male"})
    print(df)
    

    打印:

       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
    

    【讨论】:

      【解决方案2】:

      np.where需要条件作为第一个参数,如果条件满足则需要输出,第三个参数是条件不满足时输出,试试这个:

      who3['gender'] = np.where(who3['gender'] == 'f', "female", 'male')
      

      另一种解决方案是使用replace 方法:

      who3['gender'] = who3['gender'].replace({'f': 'female', 'm': 'male'})
      

      【讨论】:

      • 那么 pd.np.where 的 pd 部分就不需要了吗?
      • 是的。因为np.where 是一个 numpy 函数而不是 pandas 函数。我还为您的问题添加了另一个解决方案。
      猜你喜欢
      • 2020-10-14
      • 1970-01-01
      • 1970-01-01
      • 2019-06-11
      • 2022-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-22
      相关资源
      最近更新 更多