简体   繁体   中英

How can I access parsed dates by pd.read_csv?

I parsed my CSV data with data = pd.read_csv('Data.csv', parse_dates= True, index_col=6, date_parser = parser) Then, when I try to access the Time column doing something like data["Time"], I get a key access error. If I don't parse the data using read_csv and parse it instead after with #data['Date'] = pd.to_datetime(data['Date'], format='%m/%d/%Y %H:%M:%S') , then my graphs don't automatically have the time on the x axis if I only plot y. My end goal is to be able to have the user select the time frame of the graph, and I'm having trouble doing so because I can't access the Data column after I parse dates. Any help would be appreciated, thanks.

The sample CSV headers are these:

"Name","Date", "Data"

"Data", "05/14/2022 21:30:00", "100"

"Data", "05/14/2022 21:30:00", "100"

"Data", "05/14/2022 21:30:00", "100

Given a CSV that looks like this:

Name,Date,Data
Data,05/13/2022 21:30:00,100
Data,05/14/2022 21:30:00,100
Data,05/15/2022 21:30:00,100
Data,05/16/2022 21:30:00,100

Note: no double quotes and no space after the comma delimiter

You have several options to load the data. Below is the easiest way if the data is a timeseries (all dates in Date column are different)

import pandas as pd

data = pd.read_csv("Data.csv", parse_dates=True, index_col="Date")

The above returns a dataframe with the Date column as a DatetimeIndex with a dtype of datetime64[ns] and is accessed via data.index .

Resulting dataframe:

                     Name   Data
               Date
2022-05-13 21:30:00  Data    100        
2022-05-14 21:30:00  Data    100
2022-05-15 21:30:00  Data    100
2022-05-16 21:30:00  Data    100

You can then plot the data with a simple data.plot() .

If you want to filter what data is plot based on time, eg Only data on 05/14 and 05/15:

data[(data.index < "2022-05-16") & (data.index > "2022-05-13")].plot()

or

new_data = data[(data.index < "2022-05-16") & (data.index > "2022-05-15")]
new_data.plot()

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