pandas groupby and update with min value( pandas 分组并使用最小值更新)
本文介绍了 pandas 分组并使用最小值更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的数据帧:
dfd = pd.DataFrame({'A': ['Apple','Apple', 'Apple','Orange','Orange','Orange','Pears','Pears'],
'B': [1,2,9,6,4,3,2,1]
})
A B
0 Apple 1
1 Apple 2
2 Apple 9
3 Orange 6
4 Orange 4
5 Orange 3
6 Pears 2
7 Pears 1
预期:
A new_B old_B
0 Apple 1 1
1 Apple 1 2
2 Apple 1 9
3 Orange 3 6
4 Orange 3 4
5 Orange 3 3
6 Pears 1 2
7 Pears 1 1
预期的数据帧:new_values包含该组的最小值,对于Apple,最小列B的值是1,因此Apple的所有新值都是1,类似地,列B的Orange最小值是3,它在new_b列中被替换。
第二个预期产量: 一旦达到上述预期输出,我就必须为每个组创建SQL语句并写入文件: 基本上,迭代每一行并编写SQL查询:
sql_query= "update test_tbl "
"set id = {0}"
"where id = {1}"
"and A = '{2}' ".format(new_b,old_b,A)
print(sql_query, file=open("output.sql", "a"))
推荐答案
使用GroupBy.transform
FORSeries
,大小与原始df
相同:
dfd['new_B'] = dfd.groupby('A')['B'].transform('min')
print (dfd)
A B new_B
0 Apple 1 1
1 Apple 2 1
2 Apple 9 1
3 Orange 6 3
4 Orange 4 3
5 Orange 3 3
6 Pears 2 1
7 Pears 1 1
如果列的顺序很重要,请使用insert
和rename
:
dfd.insert(1, 'new_B', dfd.groupby('A')['B'].transform('min'))
dfd = dfd.rename(columns={'B':'old_B'})
print (dfd)
A new_B old_B
0 Apple 1 1
1 Apple 1 2
2 Apple 1 9
3 Orange 3 6
4 Orange 3 4
5 Orange 3 3
6 Pears 1 2
7 Pears 1 1
如果transform
不可能,请使用以下替代解决方案:
#aggregate by min
s = dfd.groupby('A')['B'].min()
print (s)
A
Apple 1
Orange 3
Pears 1
Name: B, dtype: int64
#insert and map
dfd.insert(1, 'new_B', dfd['A'].map(s))
dfd = dfd.rename(columns={'B':'old_B'})
print (dfd)
A new_B old_B
0 Apple 1 1
1 Apple 1 2
2 Apple 1 9
3 Orange 3 6
4 Orange 3 4
5 Orange 3 3
6 Pears 1 2
7 Pears 1 1
这篇关于 pandas 分组并使用最小值更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:pandas 分组并使用最小值更新


基础教程推荐
猜你喜欢
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 包装空间模型 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 求两个直方图的卷积 2022-01-01