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

6
  • Did you tried like df[col1].astype(str) Commented Jan 1, 2019 at 6:57
  • 5
    yes, I tried, it remains object Commented Jan 1, 2019 at 7:12
  • Can you show us a sample of the raw data and the command you're using to convert it to a pandas dataframe? Commented Jan 1, 2019 at 10:53
  • @ParvBanks Actually I'm reading that data from excel sheet but can't put sample here as it's confidential Commented Jan 2, 2019 at 6:47
  • Possible duplicate of How to convert column with dtype as object to string in Pandas Dataframe Commented May 28, 2019 at 8:21

2 Answers 2

5

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

df['column'] = df['column'].astype('string')
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

No luck still getting AttributeError: 'DataFrame' object has no attribute 'str'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.