使用总和重新索引Pandas数据框,而不是bfill或ffill

1 投票
1 回答
1024 浏览
提问于 2025-04-18 03:57

假设我是一位农民...我会定期去我的果园,采摘成熟的苹果、梨和李子。我会在一个叫做 pick_counts 的数据表里记录每天采摘的数量:

import pandas as pd
import numpy as np

np.random.seed(0)

pick_counts = pd.DataFrame(np.random.randint(0, 20, [10,3]),
                  index=pd.date_range('8/16/2004', periods=10, freq='D'), 
                  columns=['apples', 'pears', 'plums'])

在我的农场里,我有一个用来测量降雨量的杯子。每隔一段时间,我会检查自上次读数以来下了多少雨...也就是说,每次我查看杯子里的雨水时,我都会把水倒掉,这样就“重置”了。我把我的降雨读数存储在一个叫做 rainfall 的序列里:

rainfall = pd.Series(np.random.rand(4), 
                     index=pd.date_range('8/16/2004 12:15PM', 
                                         periods=4, 
                                         freq='80H'))

作为一个理智的农民,我想看看在某段时间内的降雨量是否会影响我在这段时间内采摘的水果数量。因此,我想创建一个数据表,包含 ['apples', 'pears', 'plums', 'rainfall'] 这些列,而行则是来自 rainfall 的日期。在水果的列中,我希望看到每种水果在每行所指示的时间和前一行所指示的时间之间的总数量。也就是说,每一行都应该包含自上一行以来降了多少雨,以及自上一行以来采摘了多少每种水果。

我该怎么做才合适呢?

我觉得我想做一些类似于 reindex 的操作,但使用一个叫 sum 的填充方法(这个方法并不存在)。你有什么想法吗?

1 个回答

2

你打算怎么定义降雨的时间段呢?比如说,我把8月16日定义为第一段,8月17日到8月19日定义为第二段,依此类推。

In [38]:

pick_counts['period']=(pick_counts.index.values>=rainfall.index.values[...,np.newaxis]).sum(0)
gbdf=pick_counts.groupby('period').sum()
gbdf.index=rainfall.index
gbdf['rainfall']=rainfall
print gbdf
                     apples  pears  plums  rainfall
2004-08-16 12:15:00      12     15      0  0.799159
2004-08-19 20:15:00      16     28     37  0.461479
2004-08-23 04:15:00      47     47     40  0.780529
2004-08-26 12:15:00       5     33     18  0.118274

[4 rows x 4 columns]

第一行的作用是创建一个用于表示这些时间段的列:

In [113]:

print pick_counts
            apples  pears  plums  period
2004-08-16      12     15      0       0
2004-08-17       3      3      7       1
2004-08-18       9     19     18       1
2004-08-19       4      6     12       1
2004-08-20       1      6      7       2
2004-08-21      14     17      5       2
2004-08-22      13      8      9       2
2004-08-23      19     16     19       2
2004-08-24       5     15     15       3
2004-08-25       0     18      3       3

[10 rows x 4 columns]

而这个rainfall数据框就是这样的:

In [114]:

print rainfall
2004-08-16 12:15:00    0.799159
2004-08-19 20:15:00    0.461479
2004-08-23 04:15:00    0.780529
2004-08-26 12:15:00    0.118274
Freq: 80H, dtype: float64

撰写回答