【问题标题】:Filling a column of a CSV file with a value in python用python中的值填充CSV文件的列
【发布时间】:2019-01-23 18:13:05
【问题描述】:

我有一个 CSV 文件,其中“性别”列中缺少一些字段。所以我需要使用 python 的 fillna() 函数自动填充它们。我给出的条件是,如果申请人收入大于 20000,则必须使用“性别”列中的“男性”标签更新字段。相同的代码粘贴在下面,以及与该错误相关的错误。所以,谁能帮我解决这个错误

如果数据['ApplicantIncome'] >= 20000: data['Gender'].fillna(data['Gender'] == 'Male',inplace=True)

错误如下:

ValueError                                Traceback (most recent call last)
<ipython-input-97-19fee6c4a819> in <module>
----> 1 if data['ApplicantIncome'] >= 20000:
      2     data['Gender'].fillna(data['Gender'] == 'Male',inplace=True)

~\Anaconda3\lib\site-packages\pandas\core\generic.py in __nonzero__(self)
   1574         raise ValueError("The truth value of a {0} is ambiguous. "
   1575                          "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
-> 1576                          .format(self.__class__.__name__))
   1577 
   1578     __bool__ = __nonzero__

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

【问题讨论】:

  • @PatrickArtner - 你说的完全正确。但是根据我的数据集,当我按性别绘制箱线图时,所有收入超过 20000 的人都是男性。所以这就是我使用它作为参数的唯一原因。

标签: python python-3.x pandas


【解决方案1】:

你可以mask你的系列:

df['Gender'] = df['Gender'].mask(df['Income'] >= 20000, df['Gender'].fillna('Male'))

【讨论】:

    【解决方案2】:

    使用np.where():

    import pandas as pd
    import numpy as np
    data['Gender']=np.where(data['ApplicantIncome']>= 20000,data['Gender'].fillna('Male'),data['Gender'])
    

    【讨论】:

    • @Vivek 如果对您有帮助,请不要忘记接受答案(单击对勾)。谢谢
    • 是的,我在检查它是否工作后立即做了,但它显示如下消息:感谢您的反馈!声望低于 15 人的投票将被记录,但不会更改公开显示的帖子得分。
    • @Vivek :检查此链接,您将学习如何操作。 :) How does accepting an answer work
    猜你喜欢
    • 2020-07-30
    • 1970-01-01
    • 1970-01-01
    • 2019-10-26
    • 2019-09-29
    • 1970-01-01
    • 2017-09-23
    • 1970-01-01
    • 2018-03-16
    相关资源
    最近更新 更多