Python:Pandas - 数据帧中的对象到字符串类型转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53993556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 06:14:30  来源:igfitidea点击:

Python:Pandas - Object to string type conversion in dataframe

pythonpandasdataframetype-conversiontostring

提问by Arjun Mota

I'm trying to convert object to string in my dataframe using pandas. Having following data:

我正在尝试使用 Pandas 在我的数据框中将对象转换为字符串。有以下数据:

particulars
NWCLG 545627 ASDASD KJKJKJ ASDASD
TGS/ASDWWR42045645010009 2897/SDFSDFGHGWEWER
dtype:object

while trying to convert particulars column from object to stringusing astype()[with str, |S, |S32, |S80] types, or directly using str functionsit is not converting in string (remain object) and for str methods[replacing '/' with ' ']it says AttributeError: 'DataFrame' object has no attribute 'str'

在尝试使用astype()[with str, |S, |S32, |S80] 类型或直接使用 str 函数将特定列从对象转换为字符串时,它不会在字符串(保留对象)和str 方法中进行转换[替换'/' 和 ' ']它说AttributeError: 'DataFrame' object has no attribute 'str'

using pandas 0.23.4

使用Pandas 0.23.4

Also refereed: https://github.com/pandas-dev/pandas/issues/18796

另请参考:https: //github.com/pandas-dev/pandas/issues/18796

回答by U10-Forward

You can use:

您可以使用:

df['particulars'] = df['particulars'].astype('|S')

Or:

或者:

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

Then use the below, actually strattribute could work even in your case, just you accessed it in the wrong way, you only can access it to columns (Serieses):

然后使用下面的,实际上str属性甚至在你的情况下也可以工作,只是你以错误的方式访问它,你只能访问它到列(Serieses):

df['particulars'] = df['particulars'].str.replace('/',' ')

Then now:

那么现在:

print(df)

Will be desired result.

会得到想要的结果。

Edit:

编辑:

I realized you can just make the whole code below, since objectis representing str:

我意识到你可以制作下面的整个代码,因为object它代表str

df['particulars'] = df['particulars'].astype(str).str.replace('/',' ')

回答by ParvBanks

You could read the excel specifying the dtypeas str:

您可以阅读指定dtype为的excel str

df = pd.read_excel("Excelfile.xlsx", dtype=str)

then use string replace in particularscolumn as below:

然后particulars列中使用字符串替换,如下所示:

df['particulars'] = df[df['particulars'].str.replace('/','')]

Notice that the df assignment is also a dataframe in '[]' brackets.

请注意, df 分配也是 '[]' 括号中的数据框。

When you're using the below command in your program, it returns a string which you're trying to assign to a dataframe column. Hence the error.

当您在程序中使用以下命令时,它会返回一个您尝试分配给数据框列的字符串。因此错误。

df['particulars'] = df['particulars'].str.replace('/',' ')