【问题标题】:Conversion from float (native float or numpy.float64) to integer not working从浮点数(本机浮点数或 numpy.float64)转换为整数不起作用
【发布时间】:2020-07-04 11:56:08
【问题描述】:

我有一个加载了浮点数和 NaN 的数据框。我需要将所有小数/浮点数转换为整数。我检查了所有类型都是 numpy.float64 但我转换为整数不起作用。这就是数据框的样子。

目前,我正在使用此代码尝试将所有非 NaN 更改为整数,但它不会用数据帧中的整数替换浮点数。

for i, row in df_cn.iterrows():
    for col in df_cn.columns:
        cell = row[col]
        if isinstance(cell, np.float64) and np.isnan(cell) == False:
            cell = int(cell)
            df_cn.loc[i,col] = cell

此 for 循环不会用整数替换浮点数,即使我使用了 df_cn.loc[],我也会收到此错误:

我不确定我做错了什么,我做了一个类似的过程,用类似的逻辑将字符串转换为日期时间,结果很好。也许我错过了一些非常明显的东西。非常感谢您的帮助。

【问题讨论】:

  • 您甚至需要为此使用iterrows() 吗?

标签: python pandas numpy floating-point integer


【解决方案1】:

默认情况下,如果存在 np.nan 值,Pandas 会创建一系列数字作为浮点类型:documentation

因为 NaN 是浮点数,所以即使有一个缺失值的整数列也会转换为浮点 dtype(有关更多信息,请参阅对整数 NA 的支持)。 Pandas 提供了一个可以为空的整数数组,可以通过显式请求 dtype 来使用

您需要将这些数据类型用于documentation 中提供的可空整数:

  1. Int8Dtype
  2. Int16D 类型
  3. Int32D 类型
  4. Int64D 类型

【讨论】:

    【解决方案2】:

    如果您的数据框中只有数字,您可以尝试:

    df_c = df.applymap(np.int64)
    

    但如果您的数据框可能包含非数字值,则会导致错误。

    如果你仍然喜欢使用自己的代码,试试这个:

    for i, row in df_cn.iterrows():
    for col in df_cn.columns:
        cell = row[col]
        if isinstance(cell, np.float) and not np.isnan(cell):
            cell = int(cell)
            df_cn.loc[i,col] = cell
    

    【讨论】:

      【解决方案3】:

      这应该将您的数据类型从 float 更改为 int

      for col in df_cn.columns:
          df_cn[col]=df_cn[col].astype(int)
      

      在执行此操作之前,您需要将 nan 替换为 int(例如 0) df.fillna(0, inplace=True)

      这是一个示例数据框

      df=pd.DataFrame({ "D": [1.0, np.nan, 2.0, np.nan, 3.0, np.nan, np.nan, np.nan, 7],"E": [np.nan, 4.0, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan]})
      
      df.fillna(0, inplace=True)
      for col in df.columns:
          df[col] = df[col].astype(int)
      
      D    int32
      E    int32
      dtype: object
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-03-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多