【问题标题】:AttributeError: 'Series' object has no attribute 'notna'AttributeError:“系列”对象没有属性“notna”
【发布时间】:2018-05-25 22:54:59
【问题描述】:

我有一个 csv 文件,其中包含多个包含空字符串的列。将 csv 读入 pandas 数据帧后,空字符串将转换为 NaN。

现在我想将一个字符串tag- 附加到列中已经存在的字符串,但只附加到那些具有某些值的字符串,而不是那些具有 NaN

的字符串

这就是我想要做的:

with open('file1.csv','r') as file:
    for chunk in pd.read_csv(file,chunksize=1000, header=0, names=['A','B','C','D'])
        if len(chunk) >=1:
            if chunk['A'].notna:
                chunk['A'] = "tag-"+chunk['A'].astype(str)
            if chunk['B'].notna:
                chunk['B'] = "tag-"+chunk['B'].astype(str)
            if chunk['C'].notna:
                chunk['C'] = "tag-"+chunk['C'].astype(str)
            if chunk['D'].notna:
                chunk['D'] = "tag-"+chunk['D'].astype(str)

这是我得到的错误:

AttributeError: 'Series' object has no attribute 'notna'

我想要的最终输出应该是这样的:

A,B,C,D
tag-a,tab-b,tag-c,
tag-a,tag-b,,
tag-a,,,
,,tag-c,
,,,tag-d
,tag-b,,tag-d

【问题讨论】:

  • notna 是一个函数。称它为notna()。
  • 看来错字了:(
  • @jezrael 实际上,您的回答很好。如果 OP 使用正确的版本,notna 将返回一个函数,其真实性将被评估为 true。这实际上是一个 XY 问题。
  • 仍然没有改善我在提到它时仍然遇到同样的错误notna()@COLDSPEED
  • @GabbarSingh 就用notnull()

标签: python python-3.x pandas dataframe


【解决方案1】:

我相信您需要mask 才能将tag- 添加到所有列中:

for chunk in pd.read_csv('file1.csv',chunksize=2, header=0, names=['A','B','C','D']):
    if len(chunk) >=1:
        m1 = chunk.notna()
        chunk = chunk.mask(m1, "tag-" + chunk.astype(str))
 

您需要升级到最新版本的 pandas,0.21.0。

您可以查看docs:

为了提高 pandas API 之间的一致性,我们添加了额外的顶级函数 isna() 和 notna(),它们是 isnull() 和 notnull() 的别名。命名方案现在与.dropna() 和.fillna() 等方法更加一致。此外,在所有定义了 .isnull() 和 .notnull() 方法的情况下,它们都有名为 .isna() 和 .notna() 的附加方法,这些方法包含在 Categorical、Index、Series 和 DataFrame 类中。 (GH15001)。

不推荐使用配置选项 pd.options.mode.use_inf_as_null,并添加 pd.options.mode.use_inf_as_na 作为替代。

【讨论】:

  • 我刚刚检查了我的 pandas 版本,它的 0.20.3 所以现在我将尝试升级它并重新运行代码。
  • 感谢它现在的工作 :) 原来 pandas 0.20.3 没有支持 notna() 类似功能的 pandas 系列对象
猜你喜欢
  • 2020-11-11
  • 2019-04-22
  • 2019-07-26
  • 2020-04-04
  • 2019-09-16
  • 2017-12-12
  • 2019-07-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多