我如何用零来填写Pandasgroupby列表中缺少的日期?

2024-04-25 04:22:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望采取每天的交易记录和帐户时,0交易发生天。你知道吗

这是我的初始数据帧:

df.head()
tr_timestamp  text      location
2016-01-01    cookies   TX
2016-01-01    pizza     TX
2016-01-04    apples    TX
2016-01-08    bread     TX

当我按天运行一个组时,我得到以下信息:

df_by_day = df['tr_timestamp'].groupby(df.tr_timestamp).count()
df_by_day

tr_timestamp
2016-01-01  2
2016-01-04  1
2016-01-08  1

我希望使用Python/Pandas来填充没有事务的日期,以便获得以下输出:

df_by_day_filled

tr_timestamp
2016-01-01  2
2016-01-02  0
2016-01-03  0
2016-01-04  1
2016-01-05  0
2016-01-06  0
2016-01-07  0
2016-01-08  1

我尝试了以下答案,但没有给出我需要返回的结果:

Pandas groupby for zero values

Fill Missing Dates in DataFrame with Duplicate Dates in Groupby

谢谢。你知道吗


Tags: 数据inpandasdfby记录帐户交易
2条回答

您也可以尝试:

df_by_day.asfreq('D', fill_value=0)

输出:

tr_timestamp
2016-01-01    2
2016-01-02    0
2016-01-03    0
2016-01-04    1
2016-01-05    0
2016-01-06    0
2016-01-07    0
2016-01-08    1
Freq: D, Name: tr_timestamp, dtype: int64

这是^{}操作:

df.set_index(pd.to_datetime(df.pop('tr_timestamp'))).resample('D')['text'].count()

tr_timestamp
2016-01-01    2
2016-01-02    0
2016-01-03    0
2016-01-04    1
2016-01-05    0
2016-01-06    0
2016-01-07    0
2016-01-08    1
Freq: D, Name: text, dtype: int64

如果“tr\u timestamp”不是datetime,pd.to_datetime调用确保了这一点。如果是,那么解决方案就简化为

df.dtypes

tr_timestamp    datetime64[ns]
text                    object
location                object
dtype: object

df.set_index('tr_timestamp').resample('D')['text'].count()

tr_timestamp
2016-01-01    2
2016-01-02    0
2016-01-03    0
2016-01-04    1
2016-01-05    0
2016-01-06    0
2016-01-07    0
2016-01-08    1
Freq: D, Name: text, dtype: int64

相关问题 更多 >