简体   繁体   English

Python pandas - Groupby + 单元格值的条件计数

[英]Python pandas - Groupby + Conditional count of cells values

I have a table that contains the list of parcel ids, their departure time, arrival time and type or parcel.我有一个表格,其中包含包裹 ID、出发时间、到达时间和类型或包裹的列表。

A minimum working example is given below to illustrate the table.下面给出了一个最小的工作示例来说明该表。

For each line, i am trying to get the number of parcels of similar type (ie TV or PC) which departure time is superior or equal to [the departure time of the considered line] and strictly inferior to [the arrival time of the considered line]对于每条线路,我试图获取出发时间优于或等于[所考虑线路的出发时间]并且严格低于[所考虑线路的到达时间]的类似类型(即电视或PC)的包裹数量线]

Example of input data输入数据示例

Parcel_id, departure_time, arrival_time, type
id_1, 07:00, 07:30, TV
id_2, 07:00, 07:15, PC
id_3, 07:05, 07:22, PC
id_4, 07:10, 07:45, TV
id_5, 07:15, 07:50, TV
id_6, 07:10, 07:26, PC
id_7, 07:40, 08:10, TV
id_8, 07:14, 07:46, TV
id_9, 07:14, 07:32, PC
id_10, 07:15, 07:30, PC

Example of desired output data所需输出数据示例

Parcel_id, departure_time, arrival_time, type, number_of_parcels
id_1, 07:00, 07:30, TV, 4
id_2, 07:00, 07:15, PC, 4
id_3, 07:05, 07:22, PC, 4
id_4, 07:10, 07:45, TV, 4
id_5, 07:15, 07:50, TV, 2
id_6, 07:10, 07:26, PC, 3
id_7, 07:40, 08:10, TV, 1
id_8, 07:14, 07:46, TV, 3
id_9, 07:14, 07:32, PC, 2
id_10, 07:15, 07:30, PC, 1

I am trying to use the groupby function and then apply conditions....without any success我正在尝试使用 groupby 函数,然后应用条件....没有任何成功

table['number_of_parcels']= table.groupby(['type']).cond.apply(lambda g: (g>=table['departure`_time'] & g<table['arrival_time'])).count()

Does anyone have any idea on how to crack this ?有没有人知道如何破解这个?

Thanks a lot非常感谢

This works这有效

df['number_of_parcels'] = df.groupby('type').apply(lambda x: x.apply(lambda y:(
    (x['departure_time'] >= y['departure_time']) & (x['departure_time'] < y['arrival_time'])
    ).sum(), axis=1)).droplevel(level=0)
df

Out:出去:

  Parcel_id departure_time arrival_time type  number_of_parcels
0      id_1          07:00        07:30   TV                  4
1      id_2          07:00        07:15   PC                  4
2      id_3          07:05        07:22   PC                  4
3      id_4          07:10        07:45   TV                  4
4      id_5          07:15        07:50   TV                  2
5      id_6          07:10        07:26   PC                  3
6      id_7          07:40        08:10   TV                  1
7      id_8          07:14        07:46   TV                  3
8      id_9          07:14        07:32   PC                  2
9     id_10          07:15        07:30   PC                  1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM