简体   繁体   English

Pandas DF - 循环通过 DF 以从另一列中具有共同值的行中找到一列的最小值的有效方法

[英]Pandas DF - Efficient way to loop through DF to find minimum values of one column from rows with common values in another column

I have a dataframe that looks something like:我有一个 dataframe 看起来像:

matter事情 work_date工作日期
1 1 01/01/2020 2020 年 1 月 1 日
2 2 01/02/2020 2020 年 1 月 2 日
1 1 01/04/2020 2020 年 1 月 4 日
2 2 01/05/2020 2020 年 1 月 5 日

I want a new column which finds the minimum work_date of all rows with the same matter number so that I can do some time delta calculations.我想要一个新列,它可以找到具有相同事项编号的所有行的最小工作日期,以便我可以进行一些时间增量计算。 so the final result would look like this:所以最终的结果是这样的:

matter事情 work_date工作日期 first_date第一次约会
1 1 01/01/2020 2020 年 1 月 1 日 01/01/2020 2020 年 1 月 1 日
2 2 01/02/2020 2020 年 1 月 2 日 01/02/2020 2020 年 1 月 2 日
1 1 01/04/2020 2020 年 1 月 4 日 01/01/2020 2020 年 1 月 1 日
2 2 01/05/2020 2020 年 1 月 5 日 01/02/2020 2020 年 1 月 2 日

Right now, I'm using the following code, but it is taking quite a while to run (the dataframe has approx 300k rows and I'm on an ancient computer).现在,我正在使用以下代码,但运行需要相当长的时间(dataframe 有大约 300k 行,我在一台古老的计算机上)。

min_dict = {}
def check_dict(val):
    return min_dict.setdefault(val,min(df[df['tmatter']==val]['tworkdt']))

df['first_day'] = df.apply (lambda row: check_dict(row.tmatter), axis = 1)

Is there a better way to approach this?有没有更好的方法来解决这个问题?

transform does what you want and should be fast transform做你想要的,应该很快

The steps are (1) group the rows together that have the same matter (2) for each group calculate the minimum work_date and (3) save these values as a new column.这些步骤是 (1) 将具有相同matter的行组合在一起 (2) 为每个组计算最小work_date和 (3) 将这些值保存为新列。

import pandas as pd
import io

df = pd.read_csv(io.StringIO("""
matter  work_date
1   01/01/2020
2   01/02/2020
1   01/04/2020
2   01/05/2020
"""), delim_whitespace=True)

df['first_date'] = df.groupby('matter')['work_date'].transform('min')
print(df)

在此处输入图像描述

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

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