我在pandas数据帧中对数据进行分组,并使用一些聚合函数来生成结果数据。输入数据:
A B C D E F
0 aa 5 3 2 2 2
1 aa 3 2 2 3 3
2 ac 2 0 2 7 7
3 ac 9 2 3 8 8
4 ac 2 3 7 3 3
5 ad 0 0 0 1 1
6 ad 9 9 9 9 9
7 ad 6 6 6 6 6
8 ad 3 3 3 3 3
pandas grouped函数似乎一次只对一个列进行操作,但我希望在df中生成所有列的统计信息。例如,我可以使用grouped['C'].agg函数([np平均值,len])生成列'C'的统计信息,但是如果我想在所有A-F列上生成这些统计信息呢?在
结果是:
^{pr2}$但我想要的是:
A count_B mean_B count_C mean_C count_D mean_D etc...
0 aa 2 4.000000 2 2.500000 2 2.0 etc...
1 ac 3 4.333333 3 2.500000 3 4.0
2 ad 4 4.500000 4 2.500000 4 4.5
有没有简单的方法可以在一个命令中使用聚合来完成分组?如果不是,有没有一种简单的方法可以遍历所有列并合并每个列的新聚合统计结果?在
以下是我目前为止的完整代码:
import pandas as pd
import numpy as np
import pprint as pp
test_dataframe = pd.DataFrame({
'A' : ['aa', 'aa', 'ac', 'ac', 'ac', 'ad', 'ad', 'ad', 'ad'],
'B' : [5, 3, 2, 9, 2, 0, 9, 6, 3],
'C' : [3, 2, 0, 2, 3, 0, 9, 6, 3],
'D' : [2, 2, 2, 3, 7, 0, 9, 6, 3],
'E' : [2, 3, 7, 8, 3, 1, 9, 6, 3],
'F' : [2, 3, 7, 8, 3, 1, 9, 6, 3]
})
#group, aggregate, convert object to df, sort index
grouped = test_dataframe.groupby(['A'])
grouped_stats = grouped['C'].agg([np.mean, len])
grouped_stats = pd.DataFrame(grouped_stats).reset_index()
grouped_stats.rename(columns = {'mean':'mean_C', 'len':'count_C'}, inplace=True)
grouped_stats.sort_index(axis=1, inplace=True)
print "Input: "
pp.pprint(test_dataframe)
print "Output: "
pp.pprint(grouped_stats)
您不必逐个调用
grouped['B']
grouped['C']
,只需传递整个groupby对象,pandas将对所有列应用聚合函数。在相关问题 更多 >
编程相关推荐