如何将以dtype为对象的列转换为Pandas Dataframe中的字符串 [英] How to convert column with dtype as object to string in Pandas Dataframe

查看:152
本文介绍了如何将以dtype为对象的列转换为Pandas Dataframe中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我将csv文件读取到pandas数据帧时,每一列都转换为自己的数据类型.我有一列已转换为对象.我想为此列执行字符串操作,例如拆分值和创建列表.但是这种操作是不可能的,因为它的dtype是object.有人可以让我知道将列中所有项目转换为字符串而不是对象的方法吗?

When I read a csv file to pandas dataframe, each column is cast to its own datatypes. I have a column that was converted to an object. I want to perform string operations for this column such as splitting the values and creating a list. But no such operation is possible because its dtype is object. Can anyone please let me know the way to convert all the items of a column to strings instead of objects?

我尝试了几种方法,但是没有任何效果.我使用了astype,str(),to_string等.

I tried several ways but nothing worked. I used astype, str(), to_string etc.

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

df['column'].astype(str)

推荐答案

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

since strings data types have variable length, it is by default stored as object dtype. If you want to store them as string type, you can do something like this.

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

这篇关于如何将以dtype为对象的列转换为Pandas Dataframe中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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