Python 通过标签选择范围的熊猫组上的函数
考虑以下多指标地震:Python 通过标签选择范围的熊猫组上的函数,python,pandas,Python,Pandas,考虑以下多指标地震: 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)
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)
示例
现在应该如下所示
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
对示例进行分组,并使用波数
索引在每组内选择一个范围,然后对该子组执行操作。为了澄清我的意思,我举了几个例子
这是一个基于位置的解决方案
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
组的最后to元素已求和
另一种更直接的解决方案是在组上循环:
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
给予
不管怎么说,我不太喜欢它,因为它不适合通常的熊猫风格
现在,我理想中想要的是:
example.groupby(level="pp_delay").loc[1922:1924].sum()
或者甚至是类似的
example[:, 1922:1924].sum()
但显然熊猫索引不是这样工作的。有人有更好的办法吗
干杯我会跳过
groupby
example.unstack(0).ix[1922:1924].sum()
pp_delay
-1000 0.0
-500 -0.2
-400 0.8
dtype: float64
example.unstack(0).ix[1922:1924].sum()
pp_delay
-1000 0.0
-500 -0.2
-400 0.8
dtype: float64