简体   繁体   中英

read strings from .csv file in python

I am reading a .csv file using pandas, this is my code:

import pandas as pd
df=pd.read_csv('MyFile.csv','r')
numeric_col=df.ix[:,0] #numeric values, works fine
string_col=df.ix[:,1] #string values, equals to nan

Does anyone know why I am not able to read the string column?

(or to be more accurate: I am able to read some string columns, but not others. For example, this is the first line of the csv:

20150329,3002,1,20000,32459,5100,10251181,DEADFALL,RAA,S,10251181,0

I am able to read col. 7 ( 'DEADFALL' ) but not col. 8 ( RAA )).

You can try to read the file in this way:

f = pd.read_csv('MyFile.csv',header=None)

Since it seems that your file has no header line. Your file should look then like this when reading:

         0     1   2      3      4     5         6         7    8  9   \
0  20150329  3002   1  20000  32459  5100  10251181  DEADFALL  RAA  S   

         10  11  
0  10251181   0 

Then you can access the single column by:

str_col = df[8]

or you can later rename the columns with different headers passing a list of headers string, for instance:

f.columns = [list_of_strings]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM