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

ruarlubt  于 2023-02-17  发布在  Python
关注(0)|答案(3)|浏览(297)

如何将对象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
lztngnrs

lztngnrs1#

object是能够保存字符串或任何dtype组合的默认容器。
如果您使用的是panda〈'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
wh6knrhe

wh6knrhe2#

我使用'string'而不是str使其工作

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

i5desfxk3#

您正在将其转换为strnon-null object是Pandas在某些情况下处理str的方式。
看看这个关于Pandas数据类型的article
查看关于dtype的最新官方文档。

相关问题