首页 > 解决方案 > Python - Pandas - 根据 updated_at 列创建列 valid_until

问题描述

我有一个包含indexperson_idupdated_at列的数据。我想派生一个新的数据框,该数据框将具有availablevalid_untill基于该updated_at列。基本上person_id可以重复,并且只有每个最后更新的行将person_id具有valid_untill空值。

原始数据:

期望的输出:

知道我该怎么做吗?

id=[1,2,1,1] updated_at=['12/31/2019','12/30/2019','01/15/2020','01/20/2020']

dict={'id':id,'updated_at':updated_at}

df=pd.DataFrame(dict)

标签: pythonpandas

解决方案


这应该可以解决问题(尽管 - 请不要打电话给你的专栏index- 这会使事情变得复杂):

df["updated_at"]=pd.to_datetime(df["updated_at"])

df2=df.reset_index().merge(df.reset_index(), on="person_id", suffixes=["_x", "_y"])
df2["match"]=np.logical_and(df2["index_x"].lt(df2["index_y"]), df2["updated_at_x"].lt(df2["updated_at_y"]))
df["valid_until"]=df2.loc[df2["match"]].groupby("index_x")["updated_at_y"].first()

输出:

   person_id updated_at valid_until
0          1 2019-12-31  2020-01-15
1          2 2019-12-30         NaT
2          1 2020-01-15  2020-01-20
3          1 2020-01-20         NaT

输入数据

df=pd.DataFrame({"person_id": [1,2,1,1], "updated_at": "12/31/2019 12/30/2019 01/15/2020 01/20/2020".split(" ")})

推荐阅读