我有以下 DataFrame,有超過 300 萬行:
VALID_FROM VALID_TO VALUE
0 2022-01-01 2022-01-02 5
1 2022-01-01 2022-01-03 2
2 2022-01-02 2022-01-04 7
3 2022-01-03 2022-01-06 3
我想創建一個大的 date_range,其中包含每個時間戳的值之和。
對于上面的 DataFrame,結果是:
dates val
0 2022-01-01 7
1 2022-01-02 14
2 2022-01-03 12
3 2022-01-04 10
4 2022-01-05 3
5 2022-01-06 3
但是,由于 DataFrame 有超過 300 萬行,我不想遍歷每一行,而且我不確定如何在不迭代的情況下執行此操作。有什么建議么?
目前我的代碼如下所示:
new_df = pd.DataFrame()
for idx, row in dummy_df.iterrows():
dr = pd.date_range(row["VALID_FROM"], end = row["VALID_TO"], freq = "D")
tmp_df = pd.DataFrame({"dates": dr, "val": row["VALUE"]})
new_df = pd.concat(objs=[new_df, tmp_df], ignore_index=True)
new_df.groupby("dates", as_index=False, group_keys=False).sum()
groupby 的結果將是我想要的輸出。
uj5u.com熱心網友回復:
如果性能對新行很重要,請Index.repeat使用counter by和 last aggregate創建colun :DataFrame.locdateGroupBy.cumcountsum
df['VALID_FROM'] = pd.to_datetime(df['VALID_FROM'])
df['VALID_TO'] = pd.to_datetime(df['VALID_TO'])
df1 = df.loc[df.index.repeat(df['VALID_TO'].sub(df['VALID_FROM']).dt.days 1)]
df1['dates'] = df1['VALID_FROM'] pd.to_timedelta(df1.groupby(level=0).cumcount(),unit='d')
df1 = df1.groupby('dates', as_index=False)['VALUE'].sum()
print (df1)
dates VALUE
0 2022-01-01 7
1 2022-01-02 14
2 2022-01-03 12
3 2022-01-04 10
4 2022-01-05 3
5 2022-01-06 3
uj5u.com熱心網友回復:
一種選擇是構建一個日期串列,從原始資料幀的最小值到最大值,使用帶有conditional_join的非等值連接 來獲取匹配項,最后是 groupby 和 sum:
# pip install pyjanitor
import pandas as pd
import janitor
# build the date pandas object:
dates = df.filter(like='VALID').to_numpy()
dates = pd.date_range(dates.min(), dates.max(), freq='1D')
dates = pd.Series(dates, name='dates')
# compute the inequality join between valid_from and valid_to,
# followed by the aggregation on a groupby:
(df
.conditional_join(
dates,
('VALID_FROM', 'dates', '<='),
('VALID_TO','dates', '>='),
# if you have numba installed,
# it can improve performance
use_numba=False,
df_columns='VALUE')
.groupby('dates')
.VALUE
.sum()
)
dates
2022-01-01 7
2022-01-02 14
2022-01-03 12
2022-01-04 10
2022-01-05 3
2022-01-06 3
Name: VALUE, dtype: int64
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/537304.html
上一篇:Pandasread_parquet()錯誤:pyarrow.lib.ArrowInvalid:從時間戳[us]轉換為時間戳[ns]會導致時間戳超出范圍
