gpt4 book ai didi

python - 按日期查找值并求和

转载 作者:太空宇宙 更新时间:2023-11-04 01:55:33 26 4
gpt4 key购买 nike

我有一些格式的数据:

 date_1  date_2  date_3  pay_1  pay_2  pay_3
2017-03 2017-04 2017-05 115.3 110.5 115.7
2018-03 NaT NaT 98.2 nan nan
2017-08 2017-09 NaT 200.0 200.0 nan
. . . . . .
. . . . . .

其中数据列在 datetime64 中初始,我变成了字符串,而 pay 列在 int 中。索引是唯一的格式化数字。我确保它们是独一无二的。

所以,我需要知道自基地开始之日起每个月支付了多少钱。这是我尝试过的:

group = pd.DataFrame(); group['dates']= sp.date_hw().astype(str); group['paid'] = 0
col_array = df_hw.columns

for i in range(len(group)):
for j in range(len(ind_array)):
for k in range(3):
if '-'.join(df_hw.loc[ind_array[j]][col_array[k]].split('-')[:-1]) == group.loc[i]['dates']:
group.loc[i]['paid'] = group.loc[i]['paid'] + df_hw.loc[ind_array[j]][col_array[k]+15]

基本上,group 数据框是我的结果应该存储的地方,预期的输出是:

     dates     paid 
2015-01 11452.43
2015-02 9326.32
2015-03 14398.95
. .
. .

最后,问题在于它需要花费大量时间才能完成并且没有产生任何结果。不可能没有更简单、更简单的方法来做到这一点,但我自己就是想不通。

最佳答案

首先使用 pd.wide_to_long reshape ,然后您可以毫无问题地 groupby.sum

res = pd.wide_to_long(df.reset_index(), stubnames=['date', 'pay'], 
sep='_', i='index', j='num')

res.groupby('date').sum()

输出

           pay
date
2017-03 115.3
2017-04 110.5
2017-05 115.7
2017-08 200.0
2017-09 200.0
2018-03 98.2
NaT 0.0

或者,保留完整的 datetime64(即使有天数)并使用 PeriodIndex 对整形后的月份进行分组。

res = pd.wide_to_long(df.reset_index(), stubnames=['date', 'pay'], 
sep='_', i='index', j='num')
res.groupby(pd.PeriodIndex(res.date, freq='M')).sum()

pay
date
2017-03 115.3
2017-04 110.5
2017-05 115.7
2017-08 200.0
2017-09 200.0
2018-03 98.2

关于python - 按日期查找值并求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56908685/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com