2016-08-03 112 views
1

选择考虑下面的多指标熊猫台系列:功能通过标签

import pandas as pd 
import numpy as np 

val = np.array([ 0.4, -0.6, 0.6, 0.5, -0.4, 0.2, 0.6, 1.2, -0.4]) 
inds = [(-1000, 1921.6), (-1000, 1922.3), (-1000, 1923.0), (-500, 1921.6), 
     (-500, 1922.3), (-500, 1923.0), (-400, 1921.6), (-400, 1922.3), 
     (-400, 1923.0)] 
names = ['pp_delay', 'wavenumber'] 
example = pd.Series(val) 
example.index = pd.MultiIndex.from_tuples(inds, names=names) 

example现在看起来应该

pp_delay wavenumber 
-1000  1921.6  0.4 
      1922.3  -0.6 
      1923.0  0.6 
-500  1921.6  0.5 
      1922.3  -0.4 
      1923.0  0.2 
-400  1921.6  0.6 
      1922.3  1.2 
      1923.0  -0.4 
dtype: float64 

我通过pp_delay要组例子并选择范围内的每个组使用wavenumber索引并对该子组执行操作。为了澄清我的意思,我举几个例子。

这是一个基于位置的解决方案。

example.groupby(level="pp_delay").nth(list(range(1,3))).groupby(level="pp_delay").sum() 

这给

pp_delay 
-1000 0.0 
-500 -0.2 
-400  0.8 
dtype: float64 

现在最后给每个pp_delay组的元素已经被求和。

另一种解决方案,更直接的是在循环遍历组:

delays = example.index.levels[0] 
res = np.zeros(delays.shape) 
roi = slice(1922, 1924) 
for i in range(3): 
    res[i] = example[delays[i]][roi].sum() 
res 

array([ 0. , -0.2, 0.8]) 

反正我不喜欢它,多醚,因为它不合身通常的熊猫风格。

现在我非常想是这样的:

example.groupby(level="pp_delay").loc[1922:1924].sum() 

,或者甚至像

example[:, 1922:1924].sum() 

但显然大熊猫索引不工作的方式。任何人都有更好的办法?

干杯

回答

2

我会跳过groupby

example.unstack(0).ix[1922:1924].sum() 

pp_delay 
-1000 0.0 
-500 -0.2 
-400  0.8 
dtype: float64