Skip to main content
 首页 » 编程设计

python之将 agroupby 应用于数据后对齐索引

2025年05月04日16java哥

我从《10 minutes in pandas》中读到这样一个例子

#+begin_src ipython :session alinbx :results output 
 df = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar', 
                          'foo', 'bar', 'foo', 'foo'], 
                    'B': ['one', 'one', 'two', 'three', 
                          'two', 'two', 'one', 'three'], 
                    'C': np.random.randn(8), 
                    'D': np.random.randn(8)}) 
print(df) 
#+end_src 
 
#+RESULTS: 
:      A      B         C         D 
: 0  foo    one  0.556718  0.948458 
: 1  bar    one  0.136203 -0.622480 
: 2  foo    two -1.472084 -1.269811 
: 3  bar  three  0.825478 -0.313981 
: 4  foo    two -0.179626 -1.176105 
: 5  bar    two -0.857654  2.008154 
: 6  foo    one  0.932524  0.070442 
: 7  foo  three  1.397533  1.050003 

分组,然后将 sum() 函数应用于结果组。

#+begin_src ipython :session alinbx :results output 
print(df.groupby('A').sum()) 
#+end_src 
 
#+RESULTS: 
:             C         D 
: A 
: bar  0.104028  1.071693 
: foo  1.235065 -0.397013 

问题是 A 与 B C 不对齐。

再比如,多列分组形成层次索引,同样可以应用sum函数

#+begin_src ipython :session alinbx :results output 
print(df.groupby(['A', 'B']).sum()) 
#+end_src 
 
#+RESULTS: 
:                   C         D 
: A   B 
: bar one    0.136203 -0.622480 
:     three  0.825478 -0.313981 
:     two   -0.857654  2.008154 
: foo one    1.489242  1.018899 
:     three  1.397533  1.050003 
:     two   -1.651711 -2.445916 

A、B 也不与 C、D 对齐

如何解决问题?

请您参考如下方法:

你可以只使用pandas.DataFrame.reset_index() :

print(df.groupby(['A', 'B']).sum().reset_index())