3

I have a text file containing a column of numbers:

10              
20               
40              
13               
24                
35               
44

I convert this to a pandas column, and try to convert it to string. But for some reason I can't seem to do so.

import pandas as pd

df=pd.read_csv('file.txt')
df.columns=['column1']
df['column1']=df['column1'].astype(str)
print(df['column1'])

This gives:

0    10
1    20
2    40
3    13
4    24
5    35
6    44
Name: column1, dtype: object

The dtype is still object isntead of string. Don't quite know why this is the case, since astype should convert it to string.

2
  • Does this answer your question? Convert Columns to String in Pandas
    – Red
    Commented Jul 9, 2020 at 1:44
  • No, since I already knew how to convert it to a string, I was just confused as to the printout and nomenclature.
    – samman
    Commented Jul 9, 2020 at 14:10

1 Answer 1

2

That is how pandas define the column type , there is not string type column, it belong to object

df.column1.apply(type)
0    <class 'str'>
1    <class 'str'>
2    <class 'str'>
3    <class 'str'>
4    <class 'str'>
5    <class 'str'>
Name: column1, dtype: object

DataFrame dose not str.replace

You should do

df.replace({'...':'...'}) 

Or

df['column1']=df['column1'].str.replace()
3
  • 1
    The problem is when I try to do df['column1']=df.str.replace(), I get an error AttributeError: 'DataFrame' object has no attribute 'str' implying the dataframe is still not a string. This is why i was trying to convert it to a string
    – samman
    Commented Jul 9, 2020 at 1:21
  • 1
    @samman that is for series not dataframe , I have update my answer
    – BENY
    Commented Jul 9, 2020 at 1:23
  • So do I even need to change the types to str? To try your method? Also what's the difference between df.replace and df[].str.replace
    – samman
    Commented Jul 9, 2020 at 1:26

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.