本文介绍了如何将不同的功能应用于 pandas 数据帧上的不同列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在小熊猫数据框中使用groupby,但是我想得到一些列的平均值和其他列的总和。假设我们有以下数据框: ID ABC
1 1 1 0
1 2 3 1
1 3 6 1
4 3 2 1
4 4 1 0
6 5 1 0
6 6 6 1
6 7 2 0
我想要分组ID并获得列A的平均值和其他列的总和实际上我有40多列)
我希望结果如下所示:
ID ABC
1 2 10 2
4 3.5 3 1
6 6 9 1
提前感谢
解决方案
你可以这样做:
数据:
在[127]中:df = pd .DataFrame(np.random.randint(0,10,(7,6)),columns = list('ABCDEF'))
...:df ['ID'] = np.random.choice( [1,2],len(df))
...:
在[128]中:df
输出[128]:
ABCD EF ID
0 7 7 2 2 3 0 1
1 8 4 1 3 6 8 1
2 4 7 7 2 8 4 2
3 5 9 3 6 6 1 1
4 4 6 1 7 4 6 2
5 4 5 3 8 7 6 2
6 8 4 1 8 1 0 1
解决方案:
在[129]中:fnc = {c :'sum'for c in df.columns.drop(['ID','A'])}
...:fnc ['A'] ='mean'
...:
在[130]中:fnc
Out [130]:{'A':'mean','B':'sum','C':'sum','D ':'sum','E':'sum','F':'sum'}
在[131]中:df.groupby('ID')。agg(fnc).reindex_axis (df.columns.drop('ID'),1)
出[131]:
ABCDEF
ID
1 7 24 7 19 16 9
2 4 18 11 17 19 16
I'd like to use groupby on pandas dataframe, but I want to get the mean of some columns and the sum for others. Let's say we have the following dataframe:
ID A B C
1 1 1 0
1 2 3 1
1 3 6 1
4 3 2 1
4 4 1 0
6 5 1 0
6 6 6 1
6 7 2 0
I would like to groupby ID and get the mean of column "A" and the sum of the other columns(in fact I have more than 40 columns).
I'd like the result to look like this:
ID A B C
1 2 10 2
4 3.5 3 1
6 6 9 1
Thanks in advance.
解决方案
you can do it this way:
Data:
In [127]: df = pd.DataFrame(np.random.randint(0,10, (7,6)), columns=list('ABCDEF'))
...: df['ID'] = np.random.choice([1,2], len(df))
...:
In [128]: df
Out[128]:
A B C D E F ID
0 7 7 2 2 3 0 1
1 8 4 1 3 6 8 1
2 4 7 7 2 8 4 2
3 5 9 3 6 6 1 1
4 4 6 1 7 4 6 2
5 4 5 3 8 7 6 2
6 8 4 1 8 1 0 1
Solution:
In [129]: fnc = {c:'sum' for c in df.columns.drop(['ID','A'])}
...: fnc['A'] = 'mean'
...:
In [130]: fnc
Out[130]: {'A': 'mean', 'B': 'sum', 'C': 'sum', 'D': 'sum', 'E': 'sum', 'F': 'sum'}
In [131]: df.groupby('ID').agg(fnc).reindex_axis(df.columns.drop('ID'), 1)
Out[131]:
A B C D E F
ID
1 7 24 7 19 16 9
2 4 18 11 17 19 16
这篇关于如何将不同的功能应用于 pandas 数据帧上的不同列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!