gpt4 book ai didi

python - 减少列值之间的数据框

转载 作者:太空宇宙 更新时间:2023-11-04 09:55:11 25 4
gpt4 key购买 nike

我想计算区间 col1 = 0, col2 = 1col1 = 0, col2 = 2 之间的操作最大值和最小值之间的差异以下数据框的 col3:

import pandas as pd


df = pd.DataFrame({'id':['id1','id1','id1','id1','id1','id1','id1','id1','id2','id2','id2','id2','id2','id2']
,'col1':[0,1,0,0,1,1,0,0,1,0,0,1,1,0],'col2':[1,2,2,1,2,2,2,1,2,2,1,2,2,2],'col3':[11,12,13,14,11,22,33,11,12,13,14,11,22,33]})

这看起来像这样:

    col1  col2  col3   id
0 0 1 11 id1
1 1 2 12 id1
2 0 2 13 id1
3 0 1 14 id1
4 1 2 11 id1
5 1 2 22 id1
6 0 2 33 id1
7 0 1 11 id2
8 1 2 12 id2
9 0 2 13 id2
10 0 1 14 id2
11 1 2 11 id2
12 1 2 22 id2
13 0 2 33 id2

一些额外的信息:

when col 1 is 0 and col2 is 1, this means that is the begining of a subset, when col 1 is 0 and col2 is 2 this means that is the end of a subset to compute the operation with col3 values as previously explained.

目标

通过id获取区间0-1和0-2之间的不同计算。这样我们会得到类似的东西:

# desired ouput
pd.DataFrame({'id':['id1','id1','id2','id2'], 'result':[2,22,2,22]})

id result
0 id1 2
1 id1 22
2 id2 2
3 id2 22

如果我们像以前一样读取原始数据库,我们会注意到它在 id1 中有两个区间 id(0-1 和 0-2),我们需要计算给定区间中 col3 的最大最小值。此外,我们有几个 ids ,所以最后我们会得到 0-1 和 0-2 之间的所有结果及其各自的 id 标签。

最佳答案

看起来你的 id列已经划分了您的组,您甚至不需要使用 col1col2 .

只需在 id 上分组列并应用一个 lambda 函数,该函数取组中最大值和最小值之间的差值。

>>> df.groupby('id')['col3'].apply(lambda group: group.max() - group.min()).reset_index()
id col3
0 id1 2
1 id2 22

关于python - 减少列值之间的数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46199565/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com