pandas.Series.apply中的访问索引

2024-05-16 12:43:16 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个多索引序列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)?做这种手术的推荐方法是什么?我希望获得一个新的序列,该序列的值由该函数应用于每一行和同一个多索引得到。


Tags: orandthe函数indexifdef序列
3条回答

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

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到底做了什么。

转换为DataFrame并沿行应用。您可以作为x.name访问索引。x也是一个Series现在有1个值

s.to_frame(0).apply(f, axis=1)[0]

使其成为一个帧,如果需要,返回标量(因此结果是一个系列)

设置

In [11]: s = Series([1,2,3],dtype='float64',index=['a','b','c'])

In [12]: s
Out[12]: 
a    1
b    2
c    3
dtype: float64

打印功能

In [13]: def f(x):
    print type(x), x
    return x
   ....: 

In [14]: pd.DataFrame(s).apply(f)
<class 'pandas.core.series.Series'> a    1
b    2
c    3
Name: 0, dtype: float64
<class 'pandas.core.series.Series'> a    1
b    2
c    3
Name: 0, dtype: float64
Out[14]: 
   0
a  1
b  2
c  3

因为您可以在这里返回任何内容,所以只需返回标量(通过name属性访问索引)

In [15]: pd.DataFrame(s).apply(lambda x: 5 if x.name == 'a' else x[0] ,1)
Out[15]: 
a    5
b    2
c    3
dtype: float64

相关问题 更多 >