'Python:Pandas - Object to string type conversion in dataframe

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

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

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

using pandas 0.23.4

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



Solution 1:[1]

You could read the excel specifying the dtype as str:

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

then use string replace in particulars column as below:

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

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

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('/',' ')

Solution 2:[2]

Instead of astype(str) :

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ParvBanks
Solution 2 Gino Mempin