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
Python:Pandas - Object to string type conversion in dataframe
提问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
回答by U10-Forward
You can use:
您可以使用:
df['particulars'] = df['particulars'].astype('|S')
Or:
或者:
df['particulars'] = df['particulars'].astype(str)
Then use the below, actually str
attribute could work even in your case, just you accessed it in the wrong way, you only can access it to columns (Series
es):
然后使用下面的,实际上str
属性甚至在你的情况下也可以工作,只是你以错误的方式访问它,你只能访问它到列(Series
es):
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 object
is representing str
:
我意识到你可以制作下面的整个代码,因为object
它代表str
:
df['particulars'] = df['particulars'].astype(str).str.replace('/',' ')
回答by ParvBanks
You could read the excel specifying the dtype
as str
:
您可以阅读指定dtype
为的excel str
:
df = pd.read_excel("Excelfile.xlsx", dtype=str)
then use string replace in particulars
column 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('/',' ')