将对象数据类型转换为python中的字符串问题 [英] Convert object data type to string issue in python

查看:104
本文介绍了将对象数据类型转换为python中的字符串问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将对象dtype结构转换为字符串dtype?下面的方法不起作用,用.astype

How can I convert an object dtype structure to a string dtype? The method below is not working and the column remains object after converting to a string with .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

推荐答案

object是能够容纳字符串或dtypes的任意组合的默认容器.

object is the default container capable of holding strings, or any combination of dtypes.

如果您使用的是熊猫版本< '1.0.0'这是您唯一的选择.如果您使用的是pd.__version__ >= '1.0.0',则可以使用新的实验性pd.StringDtype() dtype .作为实验,行为在将来的版本中可能会有所更改,因此使用后果自负.

If you are using a version of pandas < '1.0.0' this is your only option. If you are using pd.__version__ >= '1.0.0' then you can use the new experimental pd.StringDtype() dtype. Being experimental, the behavior is subject to change in future versions, so use at your own risk.

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

这篇关于将对象数据类型转换为python中的字符串问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆