【问题标题】:Python: resample dataframe and sumPython:重新采样数据框并求和
【发布时间】:2022-01-27 22:22:59
【问题描述】:

我有以下数据框:

df=pd.DataFrame(index=[0,1])
df['timestamp'] = ['2022-01-01 20:10:00', '2022-01-01 20:50:00']
df['currency'] = ['USD', 'USD']
df['operation'] = ['deposit', 'deposit']
df['amount'] = [0.1, 0.4]
df:
            timestamp           currency    operation   amount
       0    2022-01-01 20:10:00 USD         deposit     0.1
       1    2022-01-01 20:50:00 USD         deposit     0.4

如何按小时重新采样数据并将“数量”相加以获得以下数据框:

df:
         timestamp            currency  operation   amount
    0    2022-01-01 20:00:00  USD       deposit     0.5

使用.resample('H') 消除了货币和操作列。我该怎么做才能对“金额”列求和?

【问题讨论】:

    标签: python pandas dataframe datetime pandas-resample


    【解决方案1】:

    使用pd.Grouper 并关注agg

    out = df.groupby(pd.Grouper(key='timestamp',freq='1h')).\
              agg(lambda x : x.sum() 
                             if x.dtypes == float 
                             else x.iloc[0]).reset_index()
    Out[122]: 
                timestamp currency operation  amount
    0 2022-01-01 20:00:00      USD   deposit     0.5
    

    【讨论】:

    • 由于某种原因,我收到 TypeError:仅对 DatetimeIndex、TimedeltaIndex 或 PeriodIndex 有效,但得到了一个“Index”实例。你是如何让你的工作的?
    • 没关系,修好了。
    猜你喜欢
    • 1970-01-01
    • 2017-12-02
    • 1970-01-01
    • 2020-04-28
    • 2019-04-15
    • 2018-07-05
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    相关资源
    最近更新 更多