gpt4 book ai didi

python - 如何将计算列按多列分组?

转载 作者:行者123 更新时间:2023-12-01 06:28:45 24 4
gpt4 key购买 nike

您好,我有下面列出的这个数据框。

import pandas as pd

db_docks = pd.DataFrame(db_top_25, columns = ['from_station_id', 'to_station_id', 'hour', 'day','dpcapacity_start', 'dpcapacity_end'])

示例数据的图像,因为我无法直接嵌入它 Image of sample data as I can't embed it directly

我需要做的是创建一个按“小时”、“天”和“from_station_id”分组的新数据框。之后,我需要计算 'from_station_id' 的数量并减去 'to_station_id' 的数量,这是需要按 'hour'、'day' 和 'from_station_id' 分组的主列。

我知道我需要使用 .groupby 和最有可能的 .transform,但我不知道如何开始编写此语法,所以我真的需要帮助。

提前致谢。

编辑:

我已经测试过了

db_docks = pd.DataFrame(db_top_25.groupby(['from_station_id', 'day',
'hour'])['year'].count())
db_docks.reset_index()

它返回这个结果,这是正确的,我只需要添加“from_station_id”实例计数减去“to_station_id”实例计数列: this result, which is correct, I just need to add the column of counts of instances of 'from_station_id' minus count of instances of 'to_station_id'

回应@Kenan

import pandas as pd

data = {'from_station_id': [1,1,1,2,2,2,2,3,3],
'day': [1,1,1,1,1,2,2,2,2]
'hour': [1,1,1,1,1,2,2,2,2]
}

预期的输出是我能够知道每个“from_station_id”中出现了多少个 from_station_id 实例相对于日期和小时的计数。

最佳答案

如果您按小时from_station_id对DataFrame进行分组,那么每个组仅包含一个 from_station_id,因此没有意义计算不同值的数量。

那么也许您只想小时日期分组? (这更有意义)。

为了拥有多个组,我稍微扩展了您的数据,这样它包含两个组(按小时分组时):

   from_station_id  to_station_id  hour  day  dpcapacity_start  dpcapacity_end
0 56 78 22 4 20.0 30.0
1 66 77 22 4 23.0 11.0
2 66 77 23 4 23.0 11.0
3 110 77 23 4 23.0 31.0
4 110 289 23 4 15.0 19.0
5 81 41 23 4 39.0 19.0
6 56 77 23 4 27.0 31.0

然后,计算不同 from_station_id 数量之间的差异和from_station_id,在每个组中定义以下函数:

def dif(grp):
n1 = grp.from_station_id.unique().size
n2 = grp.from_station_id.unique().size
return n1 - n2

然后将其应用到每个组:

db_docks.groupby(['hour', 'day']).apply(dif)

结果是一个系列:

hour  day
22 4 0
23 4 1

地点:

  • 小时是每个组的键,
  • 值列(无名称)包含您的差异。

例如23 小时和 4 天的组包含:

  • 4 from_station_id(66、110、81 和 56),
  • 3 to_station_id(77、289 和 44),

所以他们的差异只是1

也许这不仅仅是您需要的,但无论如何您现在已经有了一些线索以及如何对 grouppinig 进行编程。

关于python - 如何将计算列按多列分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60005424/

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