gpt4 book ai didi

python - 组内组的长度(在 groupby 之后应用 groupby)

转载 作者:行者123 更新时间:2023-12-01 07:29:01 32 4
gpt4 key购买 nike

我面临下一个问题:我有组(按 ID),对于所有这些组,我需要应用以下代码:如果组内位置之间的距离在 3 米以内,则需要将它们添加在一起,因此将创建一个新组(代码如何创建我在下面显示的组)。现在,我想要的是距离组内的检测数量,即该组的长度。

这一切都有效,但是将其应用到 ID 组后,它给了我一个错误。

代码如下:

def group_nearby_peaks(df, col, cutoff=-3.00):
"""
This function groups nearby peaks based on location.
When peaks are within 3 meters from each other they will be added together.
"""
min_location_between_groups = cutoff

df = df.sort_values('Location')

return (
df.assign(
location_diff=lambda d: d['Location'].diff(-1).fillna(-9999),
NOD=lambda d: d[col]
.groupby(d["location_diff"].shift().lt(min_location_between_groups).cumsum())
.transform(len)
)
)
def find_relative_difference(df, peak_col, difference_col):

def relative_differences_per_ID(ID_df):
return (
spoortak_df.pipe(find_difference_peaks)
.loc[lambda d: d[peak_col]]
.pipe(group_nearby_peaks, difference_col)
)

return df.groupby('ID').apply(relative_differences_per_ID)

我得到的错误如下:

ValueError: No objects to concatenate

通过以下示例数据框,我期望得到这个结果。

    ID  Location
0 1 12.0
1 1 14.0
2 1 15.0
3 1 17.5
4 1 25.0
5 1 30.0
6 1 31.0
7 1 34.0
8 1 36.0
9 1 37.0
10 2 8.0
11 2 14.0
12 2 15.0
13 2 17.5
14 2 50.0
15 2 55.0
16 2 58.0
17 2 59.0
18 2 60.0
19 2 70.0

预期结果:

    ID  Number of detections
0 1 4
1 1 1
2 1 5
3 2 1
4 2 3
5 2 1
6 2 5

最佳答案

为 3 米内的 Location 创建 groupID s。超过 3 米的将被强制作为单个 ID,而其他的将被强制为重复 ID。最后,groupby IDscount

s = df.groupby('ID').Location.diff().fillna(0).abs().gt(3).cumsum()    
df.groupby(['ID',s]).ID.count().reset_index(name='Number of detections').drop('Location', 1)

Out[190]:
ID Number of detections
0 1 4
1 1 1
2 1 5
3 2 1
4 2 3
5 2 1
6 2 4
7 2 1

关于python - 组内组的长度(在 groupby 之后应用 groupby),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57305345/

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