6

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

Arjun Mota
  • 61
  • 1
  • 1
  • 6

2 Answers2

3

Use astype('string') instead of astype(str) :

df['column'] = df['column'].astype('string')
krasnapolsky
  • 347
  • 1
  • 16
darrahts
  • 365
  • 1
  • 10
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('/',' ')
ParvBanks
  • 1,316
  • 1
  • 9
  • 15