Cannot convert pandas column to string

Viewed 897

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.

1 Answers

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()
Related