【问题标题】:AttributeError: 'float' object has no attribute 'split'AttributeError: 'float' 对象没有属性 'split'
【发布时间】:2017-07-02 15:46:18
【问题描述】:

我正在拨打此行:

lang_modifiers = [keyw.strip() for keyw in row["language_modifiers"].split("|") if not isinstance(row["language_modifiers"], float)]

这似乎适用于 row["language_modifiers"] 是一个单词(atlas methodcentral),但当它出现时不是 nan

我认为我的if not isinstance(row["language_modifiers"], float) 可以赶上nan 出现的时间,但事实并非如此。

背景:row["language_modifiers"] 是 tsv 文件中的一个单元格,当正在解析的 tsv 中该单元格为空时,它会显示为 nan

【问题讨论】:

  • 为什么这被否决了?就这样我知道。您可以测试我在问题中包含的 3 个测试用例。

标签: python csv parsing nan


【解决方案1】:

您是对的,此类错误主要是由 NaN 表示空单元格引起的。 在应用您的进一步操作之前,在您的数据框 df 上使用此惯用语通常会过滤掉此类数据:

df_new = df[df['ColumnName'].notnull()]

或者,使用fillna() 方法将null 值估算(替换)为默认值可能更方便。 例如。所有nullNaN 都可以替换为其列的平均值

housing['LotArea'] = housing['LotArea'].fillna(housing.mean()['LotArea'])

或者可以用空字符串“”之类的值或其他默认值替换

housing['GarageCond']=housing['GarageCond'].fillna("")

【讨论】:

    【解决方案2】:

    您也可以使用df = df.dropna(thresh=n),其中n 是容差。意思是,它需要 n 个非 NA 值才能不删除行

    请注意,这种方法会删除该行

    例如:如果您有一个包含 5 列的数据框,df.dropna(thresh=5) 将删除任何没有 5 个有效值或非 Na 值的行。

    在您的情况下,您可能只想保留有效行;如果是这样,您可以将阈值设置为您拥有的列数。

    pandas documentation on dropna

    【讨论】:

      猜你喜欢
      • 2016-07-25
      • 2019-07-19
      • 2018-03-14
      • 2021-04-05
      • 2016-01-31
      • 2016-09-19
      • 2020-09-14
      • 2021-07-25
      • 2019-03-18
      相关资源
      最近更新 更多