RNA
RNA

Reputation: 153511

how to read the 1st column of a table as string?

For example, let's say I have code (in Python 3.5) looks like this:

In [234]: from io import StringIO
In [235]: f = '#a b c\n08 1 2\n9 3 4\n'
In [236]: df = pd.read_table(StringIO(f), sep=' ')
In [237]: df
Out[237]:
   #a  b  c
0   8  1  2
1   9  3  4

It reads the 1st column as int and gets rid of 0 before 8. I know we can pass dtype={'#a': str} to read it as str. However, supposedly I don't know the column name before hand, how can I read the 1st column as str type?

Upvotes: 0

Views: 72

Answers (1)

pansen
pansen

Reputation: 6663

You may use dtype with a dictionary where keys correspond to index locations:

from io import StringIO
f = '#a b c\n08 1 2\n9 3 4\n'
df = pd.read_table(StringIO(f), sep=' ', dtype={0: str})

print(df)

    #a  b   c
0   08  1   2
1   9   3   4

print(df.dtypes)

#a    object
b      int64
c      int64
dtype: object

Upvotes: 2

Related Questions