【问题标题】:How to convert a column with missing value to integer type如何将缺少值的列转换为整数类型
【发布时间】:2019-05-09 16:04:38
【问题描述】:

我想将一列转换为整数,但问题是该列包含缺失值。该列可以很好地转换为浮点数,但不能转换为整数。

示例代码:

d2 = {'location': ['NY', 'NY', 'PA', 'NY', 'PA', 'PA', 'NY'], 'dep_name': ['hr', 'mk', 'fin', 'fin', 'hr', 'fin', 'fin'], 'Duration_of_Employment' : [10, 5, 9, 8, 2, 4, 7], 'Salary' : [50000, 86000,25000, 73000, 28000, 60000, 40000], 'Days_Since_Last_Promotion': ['61', '35', '25', '98', 'NaN', '45', '22']}
df2 = pd.DataFrame(data = d2)

df2['xy']  = df2['Days_Since_Last_Promotion'].astype(float)
df2['Months_Since_Last_Promotion'] = df2['xy'] // 30

现在“Months_Since_Last_Promotion”是浮点类型。但是当我尝试将其转换为整数时,出现以下错误。

df2['Months_Since_Last_Promotion'] = df2['Months_Since_Last_Promotion'].astype(int)

ValueError: 无法将 NA 转换为整数

从错误中,我认为它是由于缺少值 Nan 并尝试解决此问题。但它没有工作,'Months_Since_Last_Promotion' 仍然显示为 float64。

df2.loc[df2['Months_Since_Last_Promotion'].notnull(), 'Months_Since_Last_Promotion'] = df2.loc[df2['Months_Since_Last_Promotion'].notnull(), 'Months_Since_Last_Promotion'].astype(int)

注意:我不能使用 fillna 来替换 NaN。目标是将列保持为整数。

【问题讨论】:

标签: python python-3.x pandas integer


【解决方案1】:

其实是有办法的:
https://pandas.pydata.org/pandas-docs/stable/user_guide/integer_na.html

在你的情况下:

df2['Months_Since_Last_Promotion'] = pd.array(df2['Months_Since_Last_Promotion'], dtype=pd.Int64Dtype())

但是,需要注意的是,其他软件可能无法将此列识别为int 列。我认为这与 NaN 在 python 中是 float 有关。

【讨论】:

    【解决方案2】:

    默认情况下,包含NaN 值的数字列存储为浮点数(即使所有其他数字都是整数) - 这是因为 pandas 中的类型转换限制。这意味着如果您想保留NaN 而不填充缺失值,则可能无法将该列转换为整数(据我所知)。以下是文档的摘录:

    "虽然 pandas 支持存储整数和布尔类型的数组, 这些类型不能存储丢失的数据。直到我们可以 切换到在 NumPy 中使用原生 NA 类型,我们已经建立了一些 “铸造规则”。当重新索引操作引入丢失数据时, 该系列将根据表中介绍的规则进行投射 下面。”

    请参考:

    https://pandas.pydata.org/pandas-docs/stable/missing_data.html#missing-data-casting-rules-and-indexing

    【讨论】:

      猜你喜欢
      • 2020-12-29
      • 1970-01-01
      • 2018-04-30
      • 1970-01-01
      • 2016-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-20
      相关资源
      最近更新 更多