简体   繁体   中英

How to select a specific date range in a csv file with pandas (again)?

I looked at the responses to this original question ( see here but doesn't seem to solve my issue.)

import pandas as pd 
import pandas_datareader.data 
import datetime
import matplotlib.pyplot as plt

df = pd.read_csv(mypath + filename,  \
    skiprows=4,index_col=0,usecols=['Day', 'Cushing OK Crude Oil Future Contract 1  Dollars per Barrel'],  \
    skipfooter=0,engine='python')

df.index = pd.to_datetime(df.index)

fig = plt.figure(figsize=plt.figaspect(0.25))
ax = fig.add_subplot(1,1,1) 

ax.grid(axis='y',color='lightgrey', linestyle='--', linewidth=0.5)
ax.grid(axis='x',color='lightgrey', linestyle='none', linewidth=0.5)

df['Cushing OK Crude Oil Future Contract 1  Dollars per 
Barrel'].plot(ax=ax,grid = True, \
color='blue',fontsize=14,legend=False) 

plt.show()

The graph turns out fine but I can't figure out a way to show only a certain date range. I have tried everything.

type(df) = pandas.core.frame.DataFrame
type(df.index) = pandas.core.indexes.datetimes.DatetimeIndex

also, the format for the column 'Day' is YYYY-MM-DD

Assuming you have a datetime index on your dataframe (it looks that way), you can slice using .loc like so:

% matplotlib inline

import pandas as pd
import numpy as np

data = pd.DataFrame({'values': np.random.rand(31)}, index = pd.date_range('2018-01-01', '2018-01-31'))

# Plot the entire dataframe.

data.plot()

# Plot a slice of the dataframe.

data.loc['2018-01-05':'2018-01-10', 'values'].plot(legend = False)

Gives:

在此处输入图片说明

The orange series is the slice.

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