简体   繁体   中英

How can I access a CSV column surrounded by whitespaces?

I have a .cvs file from where I have imported my data. I used Pandas Data frame.

timestamp ,ty,la,lo,he,acc,v,be,x,y,z
1434838676097.07,gps,48.77,-81.3838208,220.8674103,6,41.72777754,134.6484375,

I have tried everything to make it work but I could not access the "timestamp" column. I have tried

d = [0.0, 1.0, 2.0]
e = pd.Series(d, index = ['a', 'b', 'c'])
df = pd.DataFrame({'A': 1., 'B': e, 'C': pd.Timestamp('20130102')})

df.B[0] # 0.0 - fall back to position based
df.B['0'] # KeyError - no label '0' in index
df.B['a'] # 0.0 - found label 'a' in index
df.B.loc[0] # TypeError - string index queried by integer value
df.B.loc['0'] # KeyError - no label '0' in index
df.B.loc['a'] # 0.0 - found label 'a' in index
df.B.iloc[0] # 0.0 - position based query for row 0
df.B.iloc['0'] # TypeError - string can't be used for position
df.B.iloc['a'] # TypeError - string can't be used for position

You can do it "programmatically":

In [25]: df = pd.read_csv(r'C:\temp\1.csv', skipinitialspace=True)

In [26]: df.columns
Out[26]: Index(['timestamp ', 'ty', 'la', 'lo', 'he', 'acc', 'v', 'be', 'x', 'y', 'z'], dtype='object')
#   NOTE:  ---------------^    

fix:

In [27]: df.columns = df.columns.map(str.strip)

check:

In [28]: df.columns
Out[28]: Index(['timestamp', 'ty', 'la', 'lo', 'he', 'acc', 'v', 'be', 'x', 'y', 'z'], dtype='object')
#   NOTE:  ---------------^    

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