每次总和达到指定金额时如何按列分组?



我有一个这样的数据框df

x
0    8.86
1    1.12
2    0.56
3    5.99
4    3.08
5    4.15

我需要对x执行某种groupby操作,以便在每次总和达到 10 时聚合x。如果df的索引是一个datetime对象,我可以使用以下pd.Grouper

grouped = df.groupby(pd.Grouper(freq="min")
grouped["x"].sum()

它将按日期时间索引分组,然后每分钟x求和。就我而言,我没有可以使用datetime目标,因此df.groupby(pd.Grouper(freq=10))产生ValueError: Invalid frequency: 10.

应用groupby()sum()操作后,所需的输出数据帧如下所示

y
0    10.54
1    13.22

因为df元素 0-2 的总和为 10.54,元素 3-5 的总和为 13.22

每次总和达到 10 时,如何按总和对x进行分组?

这里有一种方法:

# cumulative sum and modulo 10
s = df.x.cumsum().mod(10)
# if value lower than 10, we've reached the value
m = s.diff().lt(0)
# groupby de cumsum
df.x.groupby(m.cumsum().shift(fill_value=0)).sum()
x
0    10.54
1    13.22
Name: x, dtype: float64

您可以使用 for 循环和滚动总和来执行此操作。

data_slices = [] # Store each sample
rollingSum = 0
last_t = 0
for t in range(len(df)):
rollingSum += df['x'][t] # Add the t index value to sum
if rollingSum >= 10:
data_slice = df['x'][last_t:t] # Slice of x column that sums over 10
data_slices.append(data_slice)
rollingSum = 0 # Reset the sum
last_t = t # Set this as the start index of next slice
grouped_data = pd.concat(data_slices, axis=0)

最新更新