假设我有一个MultiIndex系列s
>>> s
values
a b
1 2 0.1
3 6 0.3
4 4 0.7我想应用一个函数,它使用行的索引:
def f(x):
# conditions or computations using the indexes
if x.index[0] and ...:
other = sum(x.index) + ...
return something对于这样的函数,我如何做s.apply(f)呢?做这种操作的推荐方法是什么?我希望获得一个新的Series,其中包含在每一行和同一个MultiIndex上应用的函数所产生的值。
发布于 2013-08-19 15:51:26
在这里,您可能会发现使用where比使用apply更快:
In [11]: s = pd.Series([1., 2., 3.], index=['a' ,'b', 'c'])
In [12]: s.where(s.index != 'a', 5)
Out[12]:
a 5
b 2
c 3
dtype: float64此外,您还可以对以下任何部分使用numpy样式的逻辑/函数:
In [13]: (2 * s + 1).where((s.index == 'b') | (s.index == 'c'), -s)
Out[13]:
a -1
b 5
c 7
dtype: float64
In [14]: (2 * s + 1).where(s.index != 'a', -s)
Out[14]:
a -1
b 5
c 7
dtype: float64我建议测试速度(因为效率相对于应用将取决于功能)。虽然,我发现apply__s更易读.
https://stackoverflow.com/questions/18316211
复制相似问题