【问题标题】:Convert object data type to string issue in python在python中将对象数据类型转换为字符串问题
【发布时间】:2020-06-20 05:47:42
【问题描述】:

如何将对象 dtype 结构转换为字符串 dtype?下面的方法不起作用,在转换为带有.astype的字符串后,该列仍然是object

import pandas as pd
df = pd.DataFrame({'country': ['A', 'B', 'C', 'D', 'E']})

df.dtypes
#country    object
#dtype: object

df['county'] = df['country'].astype(str)

df.dtypes
#country    object
#dtype: object

【问题讨论】:

  • pandas V 1.0 介绍了StringDtype - 查看docs 以获取有关 dtype 的更多信息。

标签: python-3.x pandas


【解决方案1】:

object 是能够保存字符串或任何 dtypes 组合的默认容器。

如果您使用的是熊猫版本 '1.0.0',这是您唯一的选择。如果您使用的是pd.__version__ >= '1.0.0',那么您可以使用new experimental pd.StringDtype() dtype。由于是实验性的,行为可能会在未来的版本中发生变化,因此使用风险自负

df.dtypes
#country    object

# .astype(str) and .astype('str') keep the column as object. 
df['country'] = df['country'].astype(str)
df.dtypes
#country    object

df['country'] = df['country'].astype(pd.StringDtype())
df.dtypes
#country    string

【讨论】:

    【解决方案2】:

    我使用 'string' 而不是 str 让它工作

    df['country'] = df['country'].astype('string')
    df.dtypes
    #country    string
    

    【讨论】:

      【解决方案3】:

      您正在将其转换为strnon-null object 是 pandas 在某些情况下处理 str 的方式。

      查看关于 pandas 数据类型的 article

      查看最新的官方docs on dtypes

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-09
        • 1970-01-01
        • 2013-06-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多