python - pandas df中的累积计数
问题描述
我正在尝试cumulative
count
基于 a 中的两列导出 a pandas
df
。
下面是一个例子df
。我正在尝试导出count
基于Value
和Count
. 因此,当count
增加我想将其归因于相邻的value
import pandas as pd
d = ({
'Value' : ['A','A','B','C','D','A','B','A'],
'Count' : [0,1,1,2,3,3,4,5],
})
df = pd.DataFrame(d)
我用过这个:
for val in ['A','B','C','D']:
cond = df.Value.eq(val) & df.Count.eq(int)
df.loc[cond, 'Count_' + val] = cond[cond].cumsum()
如果我更改int
为特定数字,它将返回计数。Count
但是随着列的不断增加,我需要这个来读取任何数字。
我的预期输出是:
Value Count A_Count B_Count C_Count D_Count
0 A 0 0 0 0 0
1 A 1 1 0 0 0
2 B 1 1 0 0 0
3 C 2 1 0 1 0
4 D 3 1 0 1 1
5 A 3 1 0 1 1
6 B 4 1 1 1 1
7 A 5 2 1 1 1
所以就count
增加second row
so 1
to Value A
。Count
再次增加,这row 4
是第一次。和再次相同。就这样增加了。Value C
1
rows 5
7
count
row 8
A
2
解决方案
你可以使用str.get_dummies
anddiff
和cumsum
In [262]: df['Value'].str.get_dummies().multiply(df['Count'].diff().gt(0), axis=0).cumsum()
Out[262]:
A B C D
0 0 0 0 0
1 1 0 0 0
2 1 0 0 0
3 1 0 1 0
4 1 0 1 1
5 1 0 1 1
6 1 1 1 1
7 2 1 1 1
哪个是
In [266]: df.join(df['Value'].str.get_dummies()
.multiply(df['Count'].diff().gt(0), axis=0)
.cumsum().add_suffix('_Count'))
Out[266]:
Value Count A_Count B_Count C_Count D_Count
0 A 0 0 0 0 0
1 A 1 1 0 0 0
2 B 1 1 0 0 0
3 C 2 1 0 1 0
4 D 3 1 0 1 1
5 A 3 1 0 1 1
6 B 4 1 1 1 1
7 A 5 2 1 1 1
推荐阅读
- ios - xamarin iOS 使用共享项目与 HttpClient 不工作
- php - 没有根据 cakephp 中的 url 找到控制器
- hadoop-yarn - 纱线跟踪 url 包含主机名,而不是 ip
- class - 如何正确地从类中引发错误
- python - youtube api - 从视频元数据中检索“此视频中的音乐”信息?
- .net - 如何创建一个接受列表的 .Net Web 服务调用
作为输入参数? - excel - 使公式间接
- ios - Realm iOS:使用捆绑的数据库启动 Realm 的成本是多少?
- c# - C# 找不到关于自动更新文本框 WITH 计算的初学者解释
- java - 重新排列一个数组,使得 arr[i] = i