Python pandas 多索引从系列中获取信息

Python pandas multiindex getting info from series

我从时间序列创建了一个多索引 pandas 系列,现在我想读取其中的数据。在我见过的所有示例中,系列的列或级别都已命名。但是,在我的系列中并非如此。在这个多索引中,第一级是日期,第二级是一天中的小时。数据列有我要读取的值。

从我的系列中获取我想要的数据的最简单方法是什么?下面的代码应该很容易解释。

   import pandas as pd
   import numpy as np

   n = 1000
   t = pd.date_range(start ='2012-01-01', periods=n, freq='10T')
   x = np.random.randn(n)
   df = pd.Series(data=x, index=t)


   df1 = df[(df > 1) & (df < 1.5)]
   df2 = df1.groupby([df1.index.date, df1.index.hour]).count()

   df2.head(15)
   #How do I get the data out of df2?
   #For example, I want to read the data for '2012-01-02 01:00'

您可以通过在元组中提供两个标签来访问多索引系列中的元素。例如:

In [19]: df2[(datetime.date(2012,1,2), 3)]
Out[19]: 2

然而,这并不是那么方便。所以我认为在这种情况下最好不要构建多索引。
您可以将现有的多索引转换为平面索引,但我认为这里有一种更好的方法,让 groupby 略有不同。使用我可以指定的 Grouper 对象对每小时的 DatetimeIndex 进行分组:

In [120]: df2 = df1.groupby(pd.Grouper(freq='H')).count()

In [121]: df2.head()
Out[121]:
2012-01-01 02:00:00    2
2012-01-01 03:00:00    1
2012-01-01 04:00:00    2
2012-01-01 05:00:00    1
2012-01-01 06:00:00    1
Freq: H, dtype: int64

In [123]: df2['2012-01-02 03:00']
Out[123]: 2

如您所见,结果仍然有一个 DatetimeIndex,但频率为每小时一次。因此,您可以轻松地使用日期时间字符串进行索引(这在多索引方法中是不可能的)

注意:上面的groupby实际上等同于更简单的resample

df1.resample('H', how='count')