熊猫时间子集时间序列 - 日期超过一定时间

时间:2016-09-05 14:58:48

标签: python pandas indexing dataframe time-series

如果df[:'2012-01-07']返回日期低于20120107的子数据框,那么返回日期高于 20120107会是什么? df['2012-01-07':]没有...

1 个答案:

答案 0 :(得分:2)

对我而言,它运作得很完美,但在实际数据中需要按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