计算一个值的出现,直到它更改为另一个值 [英] Count appearances of a value until it changes to another value
本文介绍了计算一个值的出现,直到它更改为另一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下DataFrame:
I have the following DataFrame:
df = pd.DataFrame([10, 10, 23, 23, 9, 9, 9, 10, 10, 10, 10, 12], columns=['values'])
我想计算每个值的频率,而不是总计数-每个值的计数直到改变为另一个值。
I want to calculate the frequency of each value, but not an overall count - the count of each value until it changes to another value.
我尝试过:
df['values'].value_counts()
但是它给了我
10 6
9 3
23 2
12 1
所需的输出是
10:2
23:2
9:3
10:4
12:1
我该怎么做?
推荐答案
使用:
df = df.groupby(df['values'].ne(df['values'].shift()).cumsum())['values'].value_counts()
或:
df = df.groupby([df['values'].ne(df['values'].shift()).cumsum(), 'values']).size()
print (df)
values values
1 10 2
2 23 2
3 9 3
4 10 4
5 12 1
Name: values, dtype: int64
最后删除第一级的时间:
Last for remove first level:
df = df.reset_index(level=0, drop=True)
print (df)
values
10 2
23 2
9 3
10 4
12 1
dtype: int64
说明:
用 shift
ed不等于 ne
,然后添加 总金额
用于帮助程序系列
:
print (pd.concat([df['values'], a, b, c],
keys=('orig','shifted', 'not_equal', 'cumsum'), axis=1))
orig shifted not_equal cumsum
0 10 NaN True 1
1 10 10.0 False 1
2 23 10.0 True 2
3 23 23.0 False 2
4 9 23.0 True 3
5 9 9.0 False 3
6 9 9.0 False 3
7 10 9.0 True 4
8 10 10.0 False 4
9 10 10.0 False 4
10 10 10.0 False 4
11 12 10.0 True 5
这篇关于计算一个值的出现,直到它更改为另一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文