【发布时间】:2020-07-24 05:42:06
【问题描述】:
我正在尝试将UInt8 pandas 系列转换为新的StringDtype。
我可以执行以下操作,在 this question 中介绍,它早于新的 string dtype:
import pandas as pd
int_series = pd.Series(range(20), dtype="UInt8")
obj_series = int_series.apply(str)
这给了我一系列包含字符串的 Object dtype。
但如果我尝试将系列转换为新的 string dtype,我会收到错误:
>>> string_series = int_series.astype("string")
...
TypeError: data type not understood
请注意,首先将系列转换为Object,然后再转换为string dtype:
int_series.apply(str).astype("string")
如何将 int 系列直接转换为字符串?
我在 Python 3.7.6 上使用 pandas 1.0.3 版
更新:我在 pandas Github 页面中找到了this open issue,它描述了完全相同的问题。
上述问题中的一条评论指向another open issue,它涵盖了在不同 ExtensionArray 类型之间进行转换的所需但当前不可用的功能。
所以答案是现在无法进行直接转换,但将来可能会。
【问题讨论】:
-
我一直认为
pandas只有object作为字符串值的dtype。很有趣。 -
根据this doc,
int_series.astype('string')应该可以工作,但它没有。 -
@QuangHoang:是的,
stringdtype 是 1.0.0 版中的新内容 -
如果不使用“UInt8”而是常规int,错误更明确:
ValueError: StringArray requires a sequence of strings or pandas.NA