分组操作一般按照一定的条件将数据分组,然后对每个分组数据进行操作,然后将这些分组合并或分别输出每个分组。分组可以在行或列的方向上进行。注意:会过滤掉空值。
[En]
Grouping operation generally groups the data according to some conditions, then operates on each packet data, and then merges these groups or outputs each packet separately. Grouping can be in the direction of rows or columns. * Note * : null values will be filtered.
测试数据如下
df
Out[1]:
商品 地区 销量
0 李老吉 北京 10
1 娃啥啥 上海 13
2 康帅傅 广州 34
3 嗨非丝 深圳 25
4 娃啥啥 北京 19
5 康帅傅 上海 31
6 李老吉 重庆 24
groupby()返回的是一个生成器,可以使用for访问每一分组数据。
1、直接传入分组的键
for k ,v in df.groupby('商品'):
print(k, v)
嗨非丝 商品 地区 销量
3 嗨非丝 深圳 25
娃啥啥 商品 地区 销量
1 娃啥啥 上海 13
4 娃啥啥 北京 19
康帅傅 商品 地区 销量
2 康帅傅 广州 34
5 康帅傅 上海 31
李老吉 商品 地区 销量
0 李老吉 北京 10
6 李老吉 重庆 24
2.使用Series对象
for k, v in df.groupby(df['商品']):
print(k, v)
嗨非丝 商品 地区 销量
3 嗨非丝 深圳 25
娃啥啥 商品 地区 销量
1 娃啥啥 上海 13
4 娃啥啥 北京 19
康帅傅 商品 地区 销量
2 康帅傅 广州 34
5 康帅傅 上海 31
李老吉 商品 地区 销量
0 李老吉 北京 10
6 李老吉 重庆 24
3.多个分组键
只需传入一个列表,列表中可直接使用列名也可以使用多个Series。同时,也可以看到,k的值是元组,包含两个分组键的值。
# 也可以传入[df['商品'], df['地区']]
for k, v in df.groupby(['商品', '地区']):
print(k, v)
('嗨非丝', '深圳') 商品 地区 销量
3 嗨非丝 深圳 25
('娃啥啥', '上海') 商品 地区 销量
1 娃啥啥 上海 13
('娃啥啥', '北京') 商品 地区 销量
4 娃啥啥 北京 19
('康帅傅', '上海') 商品 地区 销量
5 康帅傅 上海 31
('康帅傅', '广州') 商品 地区 销量
2 康帅傅 广州 34
('李老吉', '北京') 商品 地区 销量
0 李老吉 北京 10
('李老吉', '重庆') 商品 地区 销量
6 李老吉 重庆 24
4.对部分列进行分组
例如,我们只想对货物进行分组和清点。不要关心区域设置字段(实际上可能还有许多其他不相关的字段)。
[En]
For example, we just want to group the goods and count them. Do not care about the locale field (there may actually be many other irrelevant fields).
上面代码也可以这样写
df['销量'].groupby(df['商品']).sum()
Out[9]:
商品
嗨非丝 25
娃啥啥 32
康帅傅 65
李老吉 34
注意,这种写法,groupby()就不能直接传入列名。因为df['销量']已经是一个Series,此时再直接传入其他列名会报KeyError。
df['销量'].groupby('商品').sum()
# KeyError: '商品'
5.通过字典进行分组
df = pd.DataFrame(np.random.randn(3, 4), columns=['A', 'B', 'C', 'D'])
dct = {'A': 'one', 'B': 'two', 'C': 'one', 'D': 'two'}
df
Out[1]:
A B C D
0 -0.364443 -0.625101 1.275733 -1.185416
1 0.350185 -0.091564 -0.314260 -0.529303
2 -0.770483 -0.187238 0.830992 1.804910
字典的功能实际上是建立这样的映射关系,即保持属于同一组的列(或行)对应的字典值相同。
[En]
The function of the dictionary is actually to establish such a mapping relationship, that is, to keep the dictionary values corresponding to the columns (or rows) belonging to the same group the same.
# 默认axis=0
df.groupby(dct, axis=1).sum()
Out[2]:
one two
0 0.911290 -1.810518
1 0.035926 -0.620867
2 0.060509 1.617673
6.层次化索引的分组
columns = pd.MultiIndex.from_arrays([['US', 'US', 'CHN', 'CHN', 'CHN'],
['A', 'B', 'A', 'B', 'C']], names=['country', 'project'])
df = pd.DataFrame(np.random.randn(3, 5), columns=columns)
print(df)
print(df.groupby(level='country', axis=1).sum())
# 输出:
country US CHN
project A B A B C
0 0.334900 -1.989492 -0.877559 -0.779063 -0.813791
1 -0.233066 -0.301358 0.924764 -0.217365 0.095670
2 0.420070 -0.658127 -0.680005 -1.604601 -0.847595
country CHN US
0 -2.470413 -1.654591
1 0.803069 -0.534424
2 -3.132200 -0.238057
7.通过函数进行分组
在实现这个功能之前,我们需要更彻底地理解传入groupby()的参数最终都是什么。虽然我们前面展现了很多种具体的书写方式,其实质都是传入一个数组,类似['A', 'B', 'A', 'C', 'B']。默认作用在index上,即第0和第2行划为一组,第1和第4行为一组。作用在列上也类似。因此,函数的作用就是根据条件生成这样的数组作为分组依据。
df = pd.DataFrame({'商品': ['李老吉', '娃啥啥', '康帅傅', '嗨非丝', '娃啥啥', '康帅傅', '李老吉'],
'地区': ['北京', '上海', '广州', '深圳', '北京', '上海', '重庆'],
'销量': [10, 13, 34, 25, 19, 31, 24]})
def fun(k):
if df['地区'][k] in ['北京', '上海']:
return '国际一线'
else:
return '国内一线'
print(df.groupby(fun).sum())
# 输出: 销量
# 国内一线 83
# 国际一线 73
事实上,上述分组操作已经使用了一些分组后操作来方便输出。例如分组求和。分组后的一些常用数值运算如下
[En]
In fact, the above grouping operations have used some post-grouping operations to facilitate output. Such as summation in groups. Some commonly used numerical operations after grouping are as follows
groupby分组后操作 操作说明sum求和count计数mean均值median中位数std,var标准差,方差min,max最小值,最大值prod乘积first,last第一个,最后一个
这些方法的使用和前面的sum一致,不再赘述。下面介绍如何对分组后数据进行自定义操作。
df = pd.DataFrame({'商品': ['李老吉', '娃啥啥', '康帅傅', '嗨非丝', '娃啥啥', '康帅傅', '李老吉'],
'地区': ['北京', '上海', '广州', '深圳', '北京', '上海', '重庆'],
'销量': [10, 13, 34, 25, 19, 31, 24]})
def fun(sdf):
if sum(sdf.iloc[:, -1]) > 40:
print('{}大卖'.format(sdf.iloc[0, 0]))
else:
print('{}还需努力'.format(sdf.iloc[0, 0]))
return 1
df.groupby(df['商品']).apply(fun)
# 输出:
嗨非丝还需努力
娃啥啥还需努力
康帅傅大卖
李老吉还需努力
商品
嗨非丝 1
娃啥啥 1
康帅傅 1
李老吉 1
基于这个基础,你可以完全自由定义处理函数,实现各种功能。当然,简单的fun完全可以用lambda实现。
补充:如果你自定义的函数除了传入分组后的df,还须接收其他参数。可以通过关键字方式传递。此处filter和apply用法是相同的。
def fun(df, s):
print(df)
print(s)
def main():
df = DataFrame([['a', 1], ['b', 2], ['a', 3]], columns=['name', 'age'])
s = '我是一个被需要的参数'
df.groupby(['name']).filter(fun, s=s)
main()
# 输出:
name age
0 a 1
2 a 3
我是一个被需要的参数
name age
1 b 2
我是一个被需要的参数
Original: https://blog.csdn.net/qq_45055172/article/details/122473640
Author: Jiangugu
Title: Pandas GroupBy数据分组处理
相关阅读
Title: ImportError: cannot import name ‘Literal‘ from ‘typing‘ (D:Anacondaenvstensorflowlibtyping.py)
报错背景:
因为安装tensorflow-gpu版本需要,我把原来的新建的anaconda环境(我的名为tensorflow)中的python3.8降为了3.7。
在导入seaborn包时,出现了以下错误:
ImportError: cannot import name 'Literal' from 'typing' (D:\Anaconda\envs\tensorflow\lib\typing.py)
原因分析:
这是由于 'Literal' 只支持python3.8版本以上的,对于python3.7并不支持。如果不想升级python版(升级真的很麻烦,可能会导致我的tensorflow-gpu版的不能用了),请看以下解决方法:
情况一:
若你只是单纯的想导入 Literal 的话:
先在你的环境中安装typing_extensions(这是针对python3.8版本以下的使用方法),安装代码如下:
pip install typing_extensions
然后使用以下代码句就可以导入了
from typing_extensions import Literal
情况二:
如果你是像我一样,想导入别的包(如seaborn),却遇到这种错误,以下是报错及解决方法:
报错如下:
解决方法:
找到你的对应路径,打开用红框提示的.py文件(打开方式随你,我是用pycharm打开的),找到对应位置,改成如下:
from typing import (
IO,
TYPE_CHECKING,
Any,
AnyStr,
Callable,
Collection,
Dict,
Hashable,
List,
Mapping,
Optional,
Sequence,
Tuple,
Type as type_t,
TypeVar,
Union,
)
from typing_extensions import (
Literal,
TypedDict,
final,
)
如果还报 ImportError: cannot import name 'xxx' from 'typing'
即再回到此.py文件下进行修改,比如 TypedDict, 不能放到上面from typing import去,否则,则会报类似错误。
我修改完_typing.py文件后,再次运行,又报了以下错误(但是好歹不是之前那个错误了)
No module named 'pandas._libs.interval'
这个错误好改,在你的环境中,安装以下:
pip install --force-reinstall pandas
至此,终于解决问题,可以导入 seaborn 啦。
Original: https://blog.csdn.net/yuhaix/article/details/124528628
Author: 小小_喻
Title: ImportError: cannot import name ‘Literal‘ from ‘typing‘ (D:Anacondaenvstensorflowlibtyping.py)

win11+AMD的cpu+3060GPU电脑安装 tensorflow-GPU+cuda11+cudnn

基于中文预训练模型和FasterTransformer的光学字符识别: Faster TrOCR

Zookeeper全解析——Paxos作为灵魂(转)

【Transformer论文模型细致讲解】

【老生谈算法】matlab实现Kmeans聚类算法源码——Kmeans聚类算法

《ROS理论与实践》学习笔记(七)机器人语音交互

Pycharm中启动Tensorflow项目找不到libcudart.so.10.1
![从零开始训练神经网络【学习笔记】[2/2]](https://www.itcode1024.com/wp-content/themes/begin/prune.php?src=https://www.itcode1024.com/wp-content/themes/begin/img/loading.png&w=280&h=210&a=&zc=1)
从零开始训练神经网络【学习笔记】[2/2]

WARNING:tensorflow: is deprecated and will be removed in a future version的解决方案

tensorflow识别水果

TensorFlow(4)-TFRecord

OpenCV-Python实战(4)——OpenCV常见图像处理技术

单片机学习:第一篇 基于Python的树莓派语音助手

win10上安装tensorflow(cpu版本)
