2016-08-03 64 views
1

我是熊貓新手。我有幾個dfs。列0中的數據是ID,列1-10是概率。我想要在dfs之間獲取列1-10的列平均值。行可能不是相同的順序。平均來自某些列的熊貓數據框

有沒有更好的方法來做到這一點比排序每個DF ID,然後使用添加/分裂DF功能?任何幫助讚賞。

非常感謝您的意見。爲了澄清,我需要平均的元素明智的 2 dfs 。即(只顯示1行中的每個DF的):

Df1:  id132456, 1, 2, 3, 4 
Df2:  id132456, 2, 2, 3, 2 
Averaged: id132456, 1.5, 2, 3, 3 
+0

熊貓採用指數很多操作(加,除等)。如果您將ID設置爲索引,則不需要排序。 – ayhan

回答

1

看起來需要concatmean

import pandas as pd 

df1 = pd.DataFrame({0:[14254,25445,34555], 
        1:[1,2,3], 
        2:[1,1,1], 
        3:[1,2,0]}) 

print (df1) 
     0 1 2 3 
0 14254 1 1 1 
1 25445 2 1 2 
2 34555 3 1 0 

df2 = pd.DataFrame({0:[14254,25445,34555], 
        2:[1,0,0], 
        1:[1,0,1], 
        3:[1,2,0]}) 

print (df2) 
     0 1 2 3 
0 14254 1 1 1 
1 25445 0 0 2 
2 34555 1 0 0 
#list of all DataFrames 
dfs = [df1, df2] 
print (pd.concat(dfs, ignore_index=True)) 
     0 1 2 3 
0 14254 1 1 1 
1 25445 2 1 2 
2 34555 3 1 0 
3 14254 1 1 1 
4 25445 0 0 2 
5 34555 1 0 0 

#select all columns without first 
print (pd.concat(dfs, ignore_index=True).ix[:,1:]) 
    1 2 3 
0 1 1 1 
1 2 1 2 
2 3 1 0 
3 1 1 1 
4 0 0 2 
5 1 0 0 

我不知道什麼樣的均值的需要,所以我加兩者:

#mean per rows 
print (pd.concat(dfs, ignore_index=True).ix[:,1:].mean(1)) 
0 1.000000 
1 1.666667 
2 1.333333 
3 1.000000 
4 0.666667 
5 0.333333 
dtype: float64 

#mean per columns 
print (pd.concat(dfs, ignore_index=True).ix[:,1:].mean()) 
1 1.333333 
2 0.666667 
3 1.000000 
dtype: float64 

也許你需要別的東西:

dfs = [df1.set_index(0), df2.set_index(0)] 
print (pd.concat(dfs, ignore_index=True, axis=1)) 
     0 1 2 3 4 5 
0      
14254 1 1 1 1 1 1 
25445 2 1 2 0 0 2 
34555 3 1 0 1 0 0 

print (pd.concat(dfs, ignore_index=True, axis=1).mean(1)) 
0 
14254 1.000000 
25445 1.166667 
34555 0.833333 
dtype: float64 

print (pd.concat(dfs, ignore_index=True, axis=1).mean()) 
0 2.000000 
1 1.000000 
2 1.000000 
3 0.666667 
4 0.333333 
5 1.000000 
dtype: float64