如何在Pandas Datafram中将dtype为对象的列转换为字符串

2024-03-29 06:47:49 发布

您现在位置:Python中文网/ 问答频道 /正文

当我将csv文件读取到pandas数据帧时,每一列都被转换为自己的数据类型。我有一个列已转换为对象。我想对这个列执行字符串操作,比如拆分值和创建列表。但由于其数据类型为object,因此不可能执行此类操作。有谁能告诉我如何将列中的所有项转换为字符串而不是对象吗?

我试了好几种方法,但都没有奏效。我使用astype,str(),来创建字符串等

a=lambda x: str(x).split(',')
df['column'].apply(a)

或者

df['column'].astype(str)

Tags: 文件csv数据对象方法字符串pandasdf
3条回答

不直接回答问题,但可能会帮助别人。

我有一个名为Volume的列,它同时具有-(无效/NaN)和用,格式化的数字

df['Volume'] = df['Volume'].astype('str')
df['Volume'] = df['Volume'].str.replace(',', '')
df['Volume'] = pd.to_numeric(df['Volume'], errors='coerce')

强制转换为字符串是应用于str.replace所必需的

pandas.Series.str.replace
pandas.to_numeric

你试过把它分配给专栏吗?

df['column'] = df['column'].astype('str') 

参照这个question,pandas数据框架存储指向字符串的指针,因此它是 “对象”。根据docs,您可以尝试:

df['column_new'] = df['column'].str.split(',') 

由于字符串数据类型具有可变长度,因此它默认存储为对象数据类型。如果要将它们存储为字符串类型,可以执行以下操作。

df['column'] = df['column'].astype('|S80') #where the max length is set at 80 bytes,

或者

df['column'] = df['column'].astype('|S') # which will by default set the length to the max len it encounters

相关问题 更多 >