如何计算大 pandas 中的以下行数 [英] How to count the number of following rows in pandas

查看:108
本文介绍了如何计算大 pandas 中的以下行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据框

A B
1 a0
2 b0
3 b1
4 a1
5 b2
6 a2

首先,我想削减 df .with startswith(a)

First,I would like to cut df.with startswith("a")

df1

A B
1 a0
2 b0
3 b1

df2

A B
4 a1
5 b2

df3

A B
6 a2

我想计数行。
并总结结果

And I would like to count the rows. And summarize the result.

我想要的结果在

   rows 
a0 3
a1 2
a2 1

如何完成?

推荐答案

您可以转换不以 a开头的单元格丢失值,然后转发填充系列,然后执行 value_counts

You can convert cells not starting with a to missing values and forward fill the series and then do value_counts:

df.B.where(df.B.str.startswith("a"), None).ffill().value_counts()
​
#a0    3
#a1    2
#a2    1
#Name: B, dtype: int64






如果您有重复的 a出现,以区分它们,您可以创建一个额外的组变量,其中 cumsum


If you have duplicated as appear, to differentiate them, you can create an additional group variable with cumsum:

start_a = df.B.str.startswith("a")
df.groupby(by = [df.B.where(start_a, None).ffill(), start_a.cumsum().rename('g')]).size()

#B   g        # here is an extra group variable to differentiate possible duplicated a rows
#a0  1    3
#a1  2    2
#a2  3    1
#dtype: int64

这篇关于如何计算大 pandas 中的以下行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆