2016-08-03 63 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