python - Python - Pandas - 根据 updated_at 列创建列 valid_until
问题描述
我有一个包含index
、person_id
和updated_at
列的数据。我想派生一个新的数据框,该数据框将具有available
并valid_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)
解决方案
这应该可以解决问题(尽管 - 请不要打电话给你的专栏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(" ")})
推荐阅读
- android - 导航控制器在 livedata 观察者中被调用两次
- python - python matplot.lib中条形图顶部的数字
- python - 检查变量是否为正整数的最紧凑/Pythonic 方法,可能的变量类型是任何变量类型,包括布尔值
- sql-server - 三表连接的group by中的列中断总和
- python - 使用基本 python 将数字列表中的连续数字分组到元组列表中(不允许使用 itertools 或更多 itertools)
- python - PyCharm 无法调试 Qt5 (PySide2) 代码 - 错误“Shiboken.ObjectType”对象不可迭代
- javascript - Html 按钮无法触发与 Document.clear 同名的事件函数
- c - 使用归并排序的多线程
- groovy - soapUI Groovy 脚本中的意外标记
- javascript - 当超链接在数据源中时,单击按钮打开超链接