访问 pandas.Series.apply 中的索引

2024-06-20

假设我有一个 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。


我不相信apply可以访问索引;它将每一行视为一个 numpy 对象,而不是一个 Series,如您所见:

In [27]: s.apply(lambda x: type(x))
Out[27]: 
a  b
1  2    <type 'numpy.float64'>
3  6    <type 'numpy.float64'>
4  4    <type 'numpy.float64'>

要解决此限制,请将索引提升为列,应用您的函数,并使用原始索引重新创建一个系列。

Series(s.reset_index().apply(f, axis=1).values, index=s.index)

其他方法可能会使用s.get_level_values,在我看来这常常变得有点难看,或者s.iterrows(),这可能会更慢——也许具体取决于什么f does.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

访问 pandas.Series.apply 中的索引 的相关文章

随机推荐