【问题标题】:How to replace a float value with NaN in pandas?如何在熊猫中用 NaN 替换浮点值?
【发布时间】:2019-04-24 21:23:42
【问题描述】:

我知道 pandas 中的替换功能:https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html

但是我已经完成了这个简单的测试,当我尝试替换浮点值时它没有按预期工作:

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(50, 4), columns=list('ABCD'))
print(df.head(n=1))

      A         B        C         D
0  1.437202  1.919894 -1.40674 -0.316737

df = df.replace(1.437202, np.nan)
print(df.head(n=1))

      A         B        C         D
0  1.437202  1.919894 -1.40674 -0.316737

如您所见,[[0],[0]] 没有任何变化...您知道这可能是什么原因造成的吗?

【问题讨论】:

    标签: python pandas replace nan


    【解决方案1】:

    只是针对特定索引的另一个技巧:

    >>> print(df.head(n=1))
              A         B         C         D
    0 -0.042839  1.701118  0.064779  1.513046
    
    >>> df['A'][0] = np.nan
    
    >>> print(df.head(n=1))
        A         B         C         D
    0 NaN  1.701118  0.064779  1.513046
    

    【讨论】:

      【解决方案2】:

      问题是浮点精度,所以使用函数numpy.isclosemask

      np.random.seed(123)
      df = pd.DataFrame(np.random.randn(50, 4), columns=list('ABCD'))
      print(df.head(n=1))
                A         B         C         D
      0 -1.085631  0.997345  0.282978 -1.506295
      
      df = df.mask(np.isclose(df.values, 0.997345))
      

      或使用numpy.where:

      arr = np.where(np.isclose(df.values, 0.997345), np.nan, df.values)
      df = pd.DataFrame(arr, index=df.index, columns=df.columns)
      

      print(df.head(n=1))
                A   B         C         D
      0 -1.085631 NaN  0.282978 -1.506295
      

      编辑:您还可以通过select_dtypes 仅获取数字列,以便使用[] 按子集进行过滤:

      np.random.seed(123)
      df = pd.DataFrame(np.random.randn(50, 4), columns=list('ABCD')).assign(E='a')
      
      cols = df.select_dtypes(np.number).columns
      df[cols] = df[cols].mask(np.isclose(df[cols].values, 0.997345))
      print(df.head(n=1))
                A   B         C         D  E
      0 -1.085631 NaN  0.282978 -1.506295  a
      

      【讨论】:

      • 确实是不错的选择,但如果列的数据类型不都是数字,它们都会失败。如果我使用字符串 df.iloc[[0], [0]] = 'random_string' 设置一个随机值,然后尝试将这两种方法应用于整个数据集,它们会返回错误 TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
      • 也许我之前应该解释过。我给出的示例仅适用于数值,但我正在寻找一种适用于任何类型特征的方法'
      • @ralvarez - 添加通用解决方案 - 仅过滤数字列并应用解决方案
      猜你喜欢
      • 2021-03-22
      • 2012-11-06
      • 2023-01-23
      • 2021-09-08
      • 2020-11-16
      • 2014-07-07
      相关资源
      最近更新 更多