gpt4 book ai didi

Python在数字序列中的2列之间获取最小最大值

转载 作者:行者123 更新时间:2023-12-04 10:17:28 26 4
gpt4 key购买 nike

我的数据框如下所示:

id  start  end
1 101 102
1 102 104
1 104 110
1 125 128
2 100 102
2 102 104
2 110 115

我希望输出为:
id  start  end
1 101 110
1 125 128
2 100 104
2 110 115

最佳答案

这是一种方法:

import numpy as np

a = df[['start', 'end']].values
# check which end is different to the start of the row bellow
m = (a[:-1] != a[1:,::-1]).all(1)
# array([False, False, True, True, False, True])
# Take the cumsum and use it to group the df rows
g = np.cumsum(np.r_[False, m])
# array([0, 0, 0, 1, 2, 2, 3], dtype=int32)
# group the df and take the first an last sample accordingly
out = df.groupby(g).agg({'id':'first', 'start':'first', 'end':'last'})
print(out)

id start end
0 1 101 110
1 1 125 128
2 2 100 104
3 2 110 115

关于Python在数字序列中的2列之间获取最小最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61008745/

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