在python中将对象数据类型转换为字符串问题

aak*_*rsh 3 python-3.x pandas

如何将对象数据类型结构转换为字符串数据类型?下面的方法不起作用,并且object在转换为字符串后该列仍然存在.astype

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
Run Code Online (Sandbox Code Playgroud)

aak*_*rsh 9

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

df['country'] = df['country'].astype('string')
df.dtypes
#country    string
Run Code Online (Sandbox Code Playgroud)


ALo*_*llz 5

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

如果您使用的是熊猫版本 <'1.0.0'这是您唯一的选择。如果您正在使用,pd.__version__ >= '1.0.0'那么您可以使用新的实验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
Run Code Online (Sandbox Code Playgroud)