![](/img/trans.png)
[英]Calculation of days till some date in DataFrame in Python Pandas?
[英]Days calculation in DataFrame in Python Pandas?
使用Series.rsub
從右側減去今天,並通過 Series.dt.days 將 timedeltas 轉換為天數,然后通過Series.dt.days
GroupBy.first
GroupBy.agg
GroupBy.last
值:
now = pd.to_datetime('today')
df = (df.assign(new = df['Date'].rsub(now).dt.days)
.groupby('ID').agg(New1 = ('new', 'first'),
New2 = ('new', 'last')))
.reset_index()
print (df)
ID New1 New2
0 1 15 13
1 2 14 11
也許嘗試groupby
:
New1 = pd.to_datetime('today') - df.groupby("ID")['Date'].min()
New2 = pd.to_datetime('today') - df.groupby("ID")['Date'].max()
df2 = pd.DataFrame({'ID': df['ID'].drop_duplicates(), 'New1': New1.tolist(), 'New2': New2.tolist()})
print(df2)
Output:
ID New1 New2
0 1 15 days 13 days
1 2 14 days 11 days
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.