2016-12-05 30 views
1

我有一個有74列1000行的數據框。我想找到每列最小的20個值(S),計算這20個值的平均值,並與一列和74列如何在熊貓數據框中找到每列最小的n值

   1    2    3  
A   2013918.153207 2010286.148942 2010903.782339 
B   1694927.195604 1648518.272357 1665890.462014  
C   1548895.121455 1594033.016024 1589820.170989 

返回結果作爲調換數據框有一個簡單的方法來在Python中執行此操作?

+1

你想[nsmallest(http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.nsmallest.html#pandas.Series.nsmallest)爲第一點,其他一切都應該是微不足道的,你可以嘗試一下,如果不成功發佈你的努力 – EdChum

回答

0

您可以使用nsmallestmean什麼工作與Series(列),所以需要apply

print (df.apply(lambda x: x.nsmallest(2).mean()).to_frame('val')) 
      val 
1 1.621911e+06 
2 1.621276e+06 
3 1.627855e+06 

numpy的解決方案

首先轉換爲numpy array,排序列,選擇行和獲得mean。最後使用DataFrame構造:

arr = df.values 
arr.sort(axis=0) 
print (arr) 
[[ 1548895.121455 1594033.016024 1589820.170989] 
[ 1694927.195604 1648518.272357 1665890.462014] 
[ 2013918.153207 2010286.148942 2010903.782339]] 

print (np.mean(arr[:2,:], axis=0)) 
[ 1621911.1585295 1621275.6441905 1627855.3165015] 

print (pd.DataFrame({'val':np.mean(arr[:2,:], axis=0)}, index=df.columns)) 
      val 
1 1.621911e+06 
2 1.621276e+06 
3 1.627855e+06 
相關問題