簡體   English   中英

熊貓:將函數應用於多索引系列

[英]Pandas: apply a function to a multiindexed series

我有一個看起來像這樣的系列“傳入”:

number.hash                               local_time         
19ace78686acf5772212d77595cb7efdb52788bf  2011-04-29 12:00:00    1
1a84708ae329e17438e8157165f91f3dec468eb6  2011-04-25 17:00:00    1
1f5b196086ca35e752eb39e4e348ae925d030af9  2011-02-16 14:00:00    1
                                          2011-02-16 15:00:00    0
                                          2011-02-16 16:00:00    0

,其中numbers.hash和local_time一起是一個MultiIndex。 現在,我想將任何函數僅應用於由numbers.hash索引的每個序列,例如,對每個由local_time和值組成的時間序列中的值求和。 我想我可以獲取number.hash索引並對其進行迭代,但是必須有一種更有效,更干凈的方法來實現。

In [36]: s = Series([1,1,1,0,0],pd.MultiIndex.from_tuples([
('A',Timestamp('20110429 12:00:00')),
('B',Timestamp('20110425 17:00:00')),
('C',Timestamp('20110216 14:00:00')),
('C',Timestamp('20110426 15:00:00')),
('C',Timestamp('20110426 16:00:00'))]))


A  2011-04-29 12:00:00    1
B  2011-04-25 17:00:00    1
C  2011-02-16 14:00:00    1
   2011-04-26 15:00:00    0
   2011-04-26 16:00:00    0
dtype: int64

按級別求和(這些向量矢量化並且非常快)

In [37]: s.sum(level=0)
Out[37]: 
A    1
B    1
C    1
dtype: int64

或分組並應用任意功能

In [38]: s.groupby(level=0).apply(lambda x: x.sum())
Out[38]: 
A    1
B    1
C    1
dtype: int64

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM