首页 > 解决方案 > pandas:将 int Series 转换为新的 StringDtype

问题描述

我正在尝试将UInt8pandas 系列转换为新的StringDtype.

我可以执行以下操作,涵盖在这个问题中,它早于新的stringdtype:

import pandas as pd
int_series = pd.Series(range(20), dtype="UInt8")
obj_series = int_series.apply(str)

这给了我一系列包含字符串的 Object dtype。

但是,如果我尝试将系列转换为新的stringdtype,则会出现错误:

>>> string_series = int_series.astype("string")
...
TypeError: data type not understood

请注意,首先将系列转换Objectstringdtype 是有效的:

int_series.apply(str).astype("string")

如何将 int 系列直接转换为字符串?

我在 Python 3.7.6 上使用 pandas 1.0.3 版


更新:我在描述完全相同的问题的 pandas Github 页面中发现了这个未解决的问题。

上述问题中的评论指向另一个未解决的问题,该问题涵盖了在不同 ExtensionArray 类型之间进行转换的所需但当前不可用的功能。

所以答案是现在不能直接转换,但将来可能会。

标签: pythonpandas

解决方案


这在文档中的示例部分中进行了解释:

与对象 dtype 数组不同,StringArray不允许非字符串值

显示以下示例的位置:

pd.array(['1', 1], dtype="string")

Traceback(最近一次调用最后一次):... ValueError:StringArray 需要字符串的 object-dtype ndarray。

唯一的解决方案似乎是Object像您所做的那样转换为 dtype然后 转换为字符串。

的源代码中StringArray也明确说明了这一点,在顶部您会看到警告:

   .. warning::
       Currently, this expects an object-dtype ndarray
       where the elements are Python strings or :attr:`pandas.NA`.
       This may change without warning in the future. Use
       :meth:`pandas.array` with ``dtype="string"`` for a stable way of
       creating a `StringArray` from any sequence.

如果您在 中检查验证步骤_validate,您将看到非字符串数组将如何失败:

def _validate(self):
    """Validate that we only store NA or strings."""
    if len(self._ndarray) and not lib.is_string_array(self._ndarray, skipna=True):
        raise ValueError("StringArray requires a sequence of strings or pandas.NA")
    if self._ndarray.dtype != "object":
        raise ValueError(
            "StringArray requires a sequence of strings or pandas.NA. Got "
            f"'{self._ndarray.dtype}' dtype instead."
        )

对于问题中的示例:

from pandas._libs import lib

lib.is_string_array(np.array(range(20)), skipna=True)
# False

推荐阅读