简体   繁体   中英

How to access elements from imported csv file with pandas in python?

Apologies for this basic question. I am new to Python and having some problem with my codes. I used pandas to load in a .csv file and having problem accessing particular elements.

 import pandas as pd
 dateYTM = pd.read_csv('Date.csv')
 print(dateYTM)
 ##  Result 
 #       Date
 # 0  20030131
 # 1  20030228
 # 2  20030331
 # 3  20030430
 # 4  20030530
 #
 # Process finished with exit code 0

How can I access say the first date? I tried many difference ways but wasn't able to achieve what I want? Many thanks.

You can use read_csv with parameter parse_dates loc , see Selection By Label :

import pandas as pd
import numpy as np
import io

temp=u"""Date,no
20030131,1
20030228,3
20030331,5
20030430,6
20030530,3
"""
#after testing replace io.StringIO(temp) to filename
dateYTM  = pd.read_csv(io.StringIO(temp), parse_dates=['Date'])
print dateYTM 
        Date  no
0 2003-01-31   1
1 2003-02-28   3
2 2003-03-31   5
3 2003-04-30   6
4 2003-05-30   3

#df.loc[index, column]

print dateYTM.loc[0, 'Date']
2003-01-31 00:00:00

print dateYTM.loc[0, 'no']
1

But if you need only one value, better is use at see Fast scalar value getting and setting :

#df.at[index, column]

print dateYTM.at[0, 'Date']
2003-01-31 00:00:00

print dateYTM.at[0, 'no']
1

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