Python:重新采样数据框并求和
Python: resample dataframe and sum
我有以下数据框:
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')
消除货币和操作列。我该怎么做才能对“金额”列求和?
先处理 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
我有以下数据框:
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')
消除货币和操作列。我该怎么做才能对“金额”列求和?
先处理 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