使用特定的开始/结束日期以及分组依据对数据框进行重新采样

时间:2019-03-07 17:37:53

标签: pandas pandas-groupby

我有一些看起来像这样的交易数据。

import pandas as pd
from io import StringIO
from datetime import datetime
from datetime import timedelta

data = """\
cust_id,datetime,txn_type,txn_amt
100,2019-03-05 6:30,Credit,25000
100,2019-03-06 7:42,Debit,4000
100,2019-03-07 8:54,Debit,1000
101,2019-03-05 5:32,Credit,25000
101,2019-03-06 7:13,Debit,5000
101,2019-03-06 8:54,Debit,2000
"""

df = pd.read_table(StringIO(data), sep=',')
df['datetime'] = pd.to_datetime(df['datetime'], format='%Y-%m-%d %H:%M:%S')
# use datetime as the dataframe index
df = df.set_index('datetime')
print(df)

                    cust_id txn_type  txn_amt
datetime                                      
2019-03-05 06:30:00      100   Credit    25000
2019-03-06 07:42:00      100    Debit     4000
2019-03-07 08:54:00      100    Debit     1000
2019-03-05 05:32:00      101   Credit    25000
2019-03-06 07:13:00      101    Debit     5000
2019-03-06 08:54:00      101    Debit     2000

我想每天对txn_amountcust_id的每种组合进行汇总(总计)txn_type的数据采样。同时,我想将索引标准化为5天(当前数据仅包含3天数据)。本质上,这就是我想产生的:

             cust_id txn_type  txn_amt
datetime    
2019-03-03    100    Credit   0
2019-03-03    100    Debit    0
2019-03-03    101    Credit   0
2019-03-03    101    Debit    0
2019-03-04    100    Credit   0
2019-03-04    100    Debit    0
2019-03-04    101    Credit   0
2019-03-04    101    Debit    0
2019-03-05    100    Credit   25000
2019-03-05    100    Debit    0
2019-03-05    101    Credit   25000
2019-03-05    101    Debit    0
2019-03-06    100    Credit   0
2019-03-06    100    Debit    4000
2019-03-06    101    Credit   0
2019-03-06    101    Debit    7000   => (note: aggregated value)
2019-03-07    100    Credit   0
2019-03-07    100    Debit    1000
2019-03-07    101    Credit   0
2019-03-07    101    Debit    0

到目前为止,我已经尝试创建新的datetime索引,并尝试重新采样,然后使用新创建的索引,如下所示:

# create a 5 day datetime index
end_dt = max(df.index).to_pydatetime().strftime('%Y-%m-%d')
start_dt = max(df.index) - timedelta(days=4)
start_dt = start_dt.to_pydatetime().strftime('%Y-%m-%d')
dt_index = pd.date_range(start=start_dt, end=end_dt, freq='1D', name='datetime')

但是,我不确定如何进行分组。没有分组的重新采样输出错误的结果:

# resample timeseries so that one row is 1 day's worth of txns
df2 = df.resample(rule='D').sum().reindex(dt_index).fillna(0)
print(df2)
            cust_id  txn_amt
datetime                    
2019-03-03      0.0      0.0
2019-03-04      0.0      0.0
2019-03-05    201.0  50000.0
2019-03-06    302.0  11000.0
2019-03-07    100.0   1000.0

那么,重新采样时如何合并cust_idtsn_type的分组?我见过this similar question,但是op的数据结构不同。

1 个答案:

答案 0 :(得分:2)

我在这里使用False,关键是设置reindex索引

Multiple