簡體   English   中英

pandas 填寫 dataframe 中給出的缺失時間間隔

[英]pandas fill missing time intervals as given in a dataframe

我有一個 DataFrame 看起來像:

gap_id 物種 時間_開始 時間停止
1個 小麥 2021-11-22 00:01:00 2021-11-22 00:03:00
2個 羊茅 2021-12-18 05:52:00 2021-12-18 05:53:00

我想擴展 DataFrame 這樣我得到的行數與每個gap_idtime_starttime_stop之間的分鍾數一樣多:

gap_id 物種 時間
1個 小麥 2021-11-22 00:01:00
1個 小麥 2021-11-22 00:02:00
1個 小麥 2021-11-22 00:03:00
2個 羊茅 2021-12-18 05:52:00
2個 羊茅 2021-12-18 05:53:00

我已經嘗試過pd.data_range方法,但我不知道如何將它與gap_id上的groupby結合起來

提前致謝

如果小 DataFrame 並且性能不重要,則為每一行生成date_range然后使用DataFrame.explode

df['time'] = df.apply(lambda x: pd.date_range(x['time_start'], x['time_stop'], freq='T'), axis=1)
df = df.drop(['time_start','time_stop'], axis=1).explode('time')

print (df)
   gap_id species                time
0       1   wheat 2021-11-22 00:01:00
0       1   wheat 2021-11-22 00:02:00
0       1   wheat 2021-11-22 00:03:00
1       2  fescue 2021-12-18 05:52:00
1       2  fescue 2021-12-18 05:53:00

對於大型數據幀,首先在分鍾內按差異startstop列重復索引,然后通過 GroupBy.cumcount 添加計數器並通過GroupBy.cumcount轉換為to_timedelta

df['time_start'] = pd.to_datetime(df['time_start'])
df['time_stop'] = pd.to_datetime(df['time_stop'])

df = (df.loc[df.index.repeat(df['time_stop'].sub(df['time_start']).dt.total_seconds() // 60 + 1)]
        .drop('time_stop', axis=1)
        .rename(columns={'time_start':'time'}))
       
td = pd.to_timedelta(df.groupby(level=0).cumcount(), unit='Min')

df['time'] += td
df = df.reset_index(drop=True)
print (df)
   gap_id species                time
0       1   wheat 2021-11-22 00:01:00
1       1   wheat 2021-11-22 00:02:00
2       1   wheat 2021-11-22 00:03:00
3       2  fescue 2021-12-18 05:52:00
4       2  fescue 2021-12-18 05:53:00

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM