My csv file is as following :
INDEX, VAL
04016170,22
04206261,11
0420677,11
df = pd.read_csv('data.csv', index_col='INDEX')
How can I force pandas to read the index as string and not as integer (to preserve the first 0
) ?
You can pass the dtype
as a param this will map the column to the passed dtype:
In [130]:
import io
import pandas as pd
t="""INDEX,VAL
04016170,22
04206261,11
0420677,11"""
df = pd.read_csv(io.StringIO(t), index_col='VAL', dtype={'INDEX':str})
df
Out[130]:
INDEX
VAL
22 04016170
11 04206261
11 0420677
In [131]:
df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 3 entries, 22 to 11
Data columns (total 1 columns):
INDEX 3 non-null object
dtypes: object(1)
memory usage: 48.0+ bytes
EDIT
OK, you can do it this way, there is a bug here when you explicitly set the index_col
in read_csv
, so you have to load the csv in first and then call set_index
after loading:
In [134]:
df = pd.read_csv(io.StringIO(t), dtype={'INDEX':str})
df = df.set_index('INDEX')
df
Out[134]:
VAL
INDEX
04016170 22
04206261 11
0420677 11
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With