2017-08-02 112 views
1

使用多個函數跨多個列(axis = 1)聚合數據框的最佳方法是什麼?使用axis = 1聚合多個函數

應用的功能列表按預期工作與默認軸= 0:

In [7]: tsdf = pd.DataFrame(np.random.randn(2, 3), columns=['A', 'B', 'C'], 
          index=pd.date_range('1/1/2000', periods=2)) 
    ...: tsdf 

Out[7]: 
        A   B   C 
2000-01-01 -0.496619 0.282351 0.222707 
2000-01-02 1.185002 -0.988669 -2.300515 

In [8]: tsdf.agg(['min', 'max', 'mean']) 
Out[8]: 
      A   B   C 
min -0.496619 -0.988669 -2.300515 
max 1.185002 0.282351 0.222707 
mean 0.344191 -0.353159 -1.038904 

但使用軸= 1時失敗:

In [9]: tsdf.agg(['min', 'max', 'mean'], axis=1) 
--------------------------------------------------------------------------- 
TypeError         Traceback (most recent call last) 
<ipython-input-9-ad4197b17943> in <module>() 
----> 1 tsdf.agg(['min', 'max', 'mean'], axis=1) 

c:\python34\lib\site-packages\pandas\core\frame.py in aggregate(self, func, axis, *args, **kwargs) 
    4152     pass 
    4153   if result is None: 
-> 4154    return self.apply(func, axis=axis, args=args, **kwargs) 
    4155   return result 
    4156 

c:\python34\lib\site-packages\pandas\core\frame.py in apply(self, func, axis, broadcast, raw, reduce, args, **kwds) 
    4260       f, axis, 
    4261       reduce=reduce, 
-> 4262       ignore_failures=ignore_failures) 
    4263    else: 
    4264     return self._apply_broadcast(f, axis) 

c:\python34\lib\site-packages\pandas\core\frame.py in _apply_standard(self, func, axis, ignore_failures, reduce) 
    4356    try: 
    4357     for i, v in enumerate(series_gen): 
-> 4358      results[i] = func(v) 
    4359      keys.append(v.name) 
    4360    except Exception as e: 

TypeError: ("'list' object is not callable", 'occurred at index 2000-01-01 00:00:00') 

有什麼我失蹤?我(天真地)認爲軸線或多或少是對稱的。應用axis = 1的多個聚合函數的最佳方法是什麼?

謝謝, 亞歷克斯

+0

我想這是在此鏈接列出的錯誤:https://github.com/pandas-dev/pandas/issues/16679 –

回答

2

我覺得這是對Pandas-Dev GitHub列出了一個錯誤:

然而,有一種變通方法:

tsdf.T.agg(['min','max','mean']).T 

輸出:

    min  max  mean 
2000-01-01 0.187605 1.707985 0.874033 
2000-01-02 -1.156725 1.121996 -0.009986 
+1

謝謝你,斯科特。很高興知道該錯誤已被報道。我昨天提出了相同的解決方法。最好的祝福。 – user2690051