【问题标题】:Changing Column Type in Pandas DataFrame to int64将 Pandas DataFrame 中的列类型更改为 int64
【发布时间】:2016-12-30 14:41:18
【问题描述】:

我正在尝试使用 .map() 在 DataFrame 中将列的数据类型从 type: object 更改为 type: int64

   df['one'] = df['one'].map(convert_to_int_with_error)

这是我的功能:

def convert_to_int_with_error(x):
    if not x in ['', None, ' ']:
        try:
            return np.int64(x)
        except ValueError as e:
            print(e)
            return None
    else:
        return None

    if not type(x) == np.int64():
        print("Not int64")
        sys.exit()

这成功完成。但是,当我在完成后检查数据类型时,它会恢复为type: float

print("%s is a %s after converting" % (key, df['one'].dtype))

【问题讨论】:

  • 您究竟把if not type(x) == np.int64(): 条件放在哪里了?你是说convert_to_int_with_error 永远不会返回None
  • 对于数字容器,None 将被视为NaN,以保持float(numerical) dtype。您需要找到一种方法来处理此类缺失值/空字符串,以便它会导致 np.int64 dtype。

标签: python pandas dataframe type-conversion series


【解决方案1】:

我认为问题在于您有问题的值从None 转换为NaN,因此int 被转换为float - 请参阅docs

您可以使用to_numericerrors='coerce' 参数代替map 将有问题的值转换为NaN

df['one'] = pd.to_numeric(df['one'], errors='coerce')

【讨论】:

  • 我包含了 try 和 except 以说明无法正确转换为 int64 的值?
  • 不幸的是,dtype int 不可能有 NaNNone 值。
猜你喜欢
  • 2018-07-26
  • 1970-01-01
  • 2019-08-12
  • 2014-09-01
  • 1970-01-01
  • 2015-05-08
  • 2021-11-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多