【问题标题】:Pandas time subset time series - dates ABOVE certain time熊猫时间子集时间序列 - 日期高于特定时间
【发布时间】:2017-01-12 23:34:04
【问题描述】:
如果df[:'2012-01-07'] 返回日期低于20120107 的子DataFrame,返回日期高于 20120107 的日期是什么? df['2012-01-07':] 不会……
【问题讨论】:
标签:
python
pandas
indexing
dataframe
time-series
【解决方案1】:
对我来说它很完美,但在实际数据中可能需要按sort_index 排序索引:
df = pd.DataFrame({'a':[0,1,2,5,4]}, index=pd.date_range('2012-01-05', periods=5))
print (df)
#if need ascending sorting
df = df.sort_index()
a
2012-01-05 0
2012-01-06 1
2012-01-07 2
2012-01-08 5
2012-01-09 4
print (df[:'2012-01-07'])
a
2012-01-05 0
2012-01-06 1
2012-01-07 2
print (df['2012-01-07':])
a
2012-01-07 2
2012-01-08 5
2012-01-09 4
df = pd.DataFrame({'a':[0,1,2,5,4]}, index=pd.date_range('2012-01-05', periods=5))
#descending sorting
df = df.sort_index(ascending=False)
print (df)
a
2012-01-09 4
2012-01-08 5
2012-01-07 2
2012-01-06 1
2012-01-05 0
print (df[:'2012-01-07'])
a
2012-01-09 4
2012-01-08 5
print (df['2012-01-07':])
a
2012-01-07 2
2012-01-06 1
2012-01-05 0