累积频率列但在条件下重置
cumulative frequency column but resetting under a condition
我有一个数据框(在 Python 上),其中包含与特定订单关联的时间和产品数量的列。
我创建了一个以 30 分钟(时间块)为间隔划分时间的列,然后我计算了该特定时间块上的产品数量(使用 groupby)。
现在我想添加一个在每个块上重新启动的累积频率。
在这个例子中,我的新列应该是 [2,3,3,5,7,...]
数据帧内每个时间块的累积和可以通过GroupBy.cumsum()
:
实现
import pandas as pd
import numpy as np
df = pd.DataFrame({
'N Products' : [2, 1, 3, 5, 2],
'Block of Time' : ['12:30:00', '12:30:00', '13:30:00', '14:00:00', '14:00:00'],
'Products on Block': [3, 3, 3, 7, 7],
})
print(df)
# N Products Block of Time Products on Block
#0 2 12:30:00 3
#1 1 12:30:00 3
#2 3 13:30:00 3
#3 5 14:00:00 7
#4 2 14:00:00 7
输出:
df['Cumulative Products'] = df.groupby('Block of Time')['N Products'].cumsum()
print(df)
# N Products Block of Time Products on Block Cumulative Products
#0 2 12:30:00 3 2
#1 1 12:30:00 3 3
#2 3 13:30:00 3 3
#3 5 14:00:00 7 5
#4 2 14:00:00 7 7
CDF 图:
df['Cumulative Products'].hist(cumulative = True)
您可以像这样计算每个组的 cumsum:
df.groupby('Block of Time')['N Products'].cumsum()
产生以下结果:
0 2
1 3
2 3
3 5
4 7
Name: N Products, dtype: int64
我有一个数据框(在 Python 上),其中包含与特定订单关联的时间和产品数量的列。
我创建了一个以 30 分钟(时间块)为间隔划分时间的列,然后我计算了该特定时间块上的产品数量(使用 groupby)。
现在我想添加一个在每个块上重新启动的累积频率。
在这个例子中,我的新列应该是 [2,3,3,5,7,...]
数据帧内每个时间块的累积和可以通过GroupBy.cumsum()
:
import pandas as pd
import numpy as np
df = pd.DataFrame({
'N Products' : [2, 1, 3, 5, 2],
'Block of Time' : ['12:30:00', '12:30:00', '13:30:00', '14:00:00', '14:00:00'],
'Products on Block': [3, 3, 3, 7, 7],
})
print(df)
# N Products Block of Time Products on Block
#0 2 12:30:00 3
#1 1 12:30:00 3
#2 3 13:30:00 3
#3 5 14:00:00 7
#4 2 14:00:00 7
输出:
df['Cumulative Products'] = df.groupby('Block of Time')['N Products'].cumsum()
print(df)
# N Products Block of Time Products on Block Cumulative Products
#0 2 12:30:00 3 2
#1 1 12:30:00 3 3
#2 3 13:30:00 3 3
#3 5 14:00:00 7 5
#4 2 14:00:00 7 7
CDF 图:
df['Cumulative Products'].hist(cumulative = True)
您可以像这样计算每个组的 cumsum:
df.groupby('Block of Time')['N Products'].cumsum()
产生以下结果:
0 2
1 3
2 3
3 5
4 7
Name: N Products, dtype: int64