如何再次使用熊猫在csv文件中选择特定的日期范围?

时间:2018-07-01 22:02:51

标签: python pandas dataframe

我查看了对原始问题的回答(see here,但似乎无法解决我的问题。)

var Cat = {
  create: function(firstName, lastName, color){
    var self = Object.create(this);
    Object.defineProperty(self,'name', {configurable: false, value: {}});
    self.name.first = firstName;
    self.name.last = lastName;
    Object.freeze(self.name);
    Object.freeze(self.color);
    return self;
  },
  name: {first: '', last: ''},
  color: ''
}

var cat = Cat.create('frisky','smith','white');
console.log(cat.name);

该图显示很好,但我想不出一种仅显示特定日期范围的方法。我已经尝试了一切。

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()

此外,列type(df) = pandas.core.frame.DataFrame type(df.index) = pandas.core.indexes.datetimes.DatetimeIndex 的格式为'Day'

1 个答案:

答案 0 :(得分:0)

假设数据框上有一个日期时间索引(看起来像那样),则可以像这样使用.loc进行切片:

% 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)

礼物:

enter image description here

橙色系列是切片。