简体   繁体   中英

How to perform groupby in one column and count distinct values of another column in each group in pandas

I have a data frame as show below, which has only four columns.

在此处输入图像描述

I want to count the number of parts in 'Line_type' column in each work order group and divide the work_duration by the count of parts and fill a new column named 'part_work_hours' by the resultant of the division only where line_type==parts.

Output data frame is shown below.

在此处输入图像描述

After the conditions were extracted, they were grouped and tabulated.

df['part_work_hour'] = df[df['Line_Type'] == 'parts'].groupby(['Work_Order_Number', 'Line_Type'])['Work_Duration'].transform(lambda x: x.mean() / x.count())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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