近日学习pandas时,对于其中的groupby()函数以及相关的一些操作查了一些资料,现总结一下以供后面翻阅
我觉得这个里面比较重要的还是对
组对象的遍历
,以及
get_group()操作
准备:数据及pandas
先来导入数据
import pandas as pd
import numpy as np
df = pd.DataFrame({‘A’: [‘foo’, ‘bar’, ‘foo’, ‘bar’,
‘foo’, ‘bar’, ‘foo’, ‘foo’],
‘B’: [‘one’, ‘one’, ‘two’, ‘three’,
‘two’, ‘two’, ‘one’, ‘three’],
‘C’: np.random.randn(8),
‘D’: np.random.randn(8)})
df
输出结果:
groupby()介绍
groupby()是一个主要用于分组的函数,可以用于拆分、转换、合并等等。下面根据练习时所用到的功能进行介绍
1、groupby对象属性
我们对dataframe使用groupby函数,返回的结果不再是一个dataframe,而是一个字典。并且无法直接将groupby()之后的结果显示出来,需要借助一些方法:
print(df.groupby(‘A’))
print(df.groupby(‘A’).groups)
{‘bar’: Int64Index([1, 3, 5], dtype=’int64′),
‘foo’: Int64Index([0, 2, 4, 6, 7], dtype=’int64′)}
2、基本操作
可以进行求和、求均值等一系列操作;亦可称为分组总汇
arrays = [[‘bar’, ‘bar’, ‘baz’, ‘baz’, ‘foo’, ‘foo’, ‘qux’, ‘qux’],
[‘one’, ‘two’, ‘one’, ‘two’, ‘one’, ‘two’, ‘one’, ‘two’]]
index = pd.MultiIndex.from_arrays(arrays, names=[‘first’, ‘second’])
df = pd.DataFrame({‘A’: [1, 1, 1, 1, 2, 2, 3, 3],
‘B’: np.arange(8)},
index=index)
df
AB
firstsecond
barone10
two11
bazone12
two13
fooone24
two25
quxone36
two37
下面这个是按照second和A列进行分组:
解释:比如对于B列中第一个数2,他是有one 1所对应的两个数0 和 2相加得到的,因为是.sum()嘛。
df.groupby([pd.Grouper(level=1), ‘A’]).sum()
输出结果:
B
secondA
one12
24
36
two14
25
37
3、遍历组
有了GroupBy对象,就可以对其进行遍历,其功能类似于itertools.groupby():
df = pd.DataFrame({‘A’: [‘foo’, ‘bar’, ‘foo’, ‘bar’,
‘foo’, ‘bar’, ‘foo’, ‘foo’],
‘B’: [‘one’, ‘one’, ‘two’, ‘three’,
‘two’, ‘two’, ‘one’, ‘three’],
‘C’: np.random.randn(8),
‘D’: np.random.randn(8)})
grouped = df.groupby(‘A’)
for name, group in grouped:
print(name)
print(group)
输出结果为:
bar
A B C D
1 bar one 0.182209 -2.398974
3 bar three 1.140349 0.185708
5 bar two -1.153971 -0.581224
foo
A B C D
0 foo one 0.153283 -0.125286
2 foo two 0.555652 -1.174632
4 foo two -1.820088 1.996878
6 foo one 1.218933 0.387911
7 foo three 1.624191 -0.007450
4、选择组(get_group()函数)
4.1 可以使用get_group()函数得到某个组
grouped.get_group(‘bar’)
输出结果:
A B C D
1barone 0.182209-2.398974
3barthree1.1403490.185708
5bartwo -1.153971-0.581224
4.2 也可以选择多个
df.groupby([‘A’, ‘B’]).get_group((‘bar’, ‘one’))
输出结果
ABCD
1barone0.182209-2.398974
欢迎各位大佬对本文提出改进意见
参考
pandas的groupby函数
https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html#groupby-object-attributes
Original: https://blog.csdn.net/weixin_39713538/article/details/113471787
Author: weixin_39713538
Title: pandas python groupby_Python学习笔记——pandas库中groupby的相关操作
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/756240/
转载文章受原作者版权保护。转载请注明原作者出处!