在Python中使用DataFrame中的日期列?
我的数据框架如下所示:在Python中使用DataFrame中的日期列?,python,pandas,dataframe,date,Python,Pandas,Dataframe,Date,我的数据框架如下所示: rng = pd.date_range('2020-12-01', periods=5, freq='D') df = pd.DataFrame({"ID" : [1, 2, 2, 1, 3], "status" : ["acc", "rem", "rem", "acc", "other"], &
rng = pd.date_range('2020-12-01', periods=5, freq='D')
df = pd.DataFrame({"ID" : [1, 2, 2, 1, 3],
"status" : ["acc", "rem", "rem", "acc", "other"], "date" : rng})
我需要创建带有列的DataFrame:
rng = pd.date_range('2020-12-01', periods=5, freq='D')
df = pd.DataFrame({"ID" : [1, 2, 2, 1, 3],
"status" : ["acc", "rem", "rem", "acc", "other"], "date" : rng})
像这样:
In [2608]: t = pd.to_datetime('today').normalize()
In [2615]: In [2627]: x = abs(df.groupby(['ID', 'status'])['date'].max() - t).dt.days.reset_index()
In [2619]: y = x.pivot('ID', 'status', 'date')
In [2620]: y
Out[2620]:
status acc other rem
ID
1 24.0 NaN NaN
2 NaN NaN 25.0
3 NaN 23.0 NaN
注意:您可以将acc
、rem
重命名为New1
和New2
。为了更好地理解,我保留了它。代码:
df=df.groupby(['status'])['date'].agg('last').reset_index()
df['diff']=abs(pd.to_datetime('today').day-df['date'].dt.day)
df_final=df.pivot(columns='status',values='diff')
输出:
df_final
Out[104]:
status acc other rem
0 24.0 NaN NaN
1 NaN 23.0 NaN
2 NaN NaN 25.0
值
24
和25
是如何产生的?您能解释一下逻辑吗?今天的日期是28.12,所以我们从04.12(ID1中的最后一份acc协议)起有24天,从03.12(ID2中的最后一份rem协议)起有25天