简体   繁体   English

如何在python中的数据框列上使用正则表达式进行分组?

[英]How to do a groupby with a regex over a dataframe column in python?

I have a table dataframe called clientesv with column called COBERTURA whose values are:我有一个名为clientesv的表数据框,其中包含名为COBERTURA的列,其值为:

clientesv.groupby('COBERTURA').size()

COBERTURA
          
A        9174
A3          1
B        1148
B0        179
B1       3922
B2          3
B3       1971
C        1511
C1       1065
C3        359
C4        145
C5         22
C6         87
C7        493
C8        174
D1         12
D2      16016
E          62
E1          5
M B      2751
M P      3080
M10     10281
M15      5187
M5       3765
dtype: int64

I would like to summarise using a Regular Expression in the Groupby so the result is:我想在 Groupby 中使用正则表达式进行总结,结果是:

A  (total amount of A + A0)
B  (total amount of B0, B1, B2, B3)
C  etc
D
E 
M

I tried to do something like this:我试图做这样的事情:

clientesv.groupby(clientesv.COBERTURA.str.contains(r'\A', regex=True)).size()

But this expression only summarise values for A so I don't know how to follow...但是这个表达式只总结了 A 的值,所以我不知道如何遵循......

Try ^(\\D) to get all the non-digit characters at the beginning of the strings.尝试^(\\D)获取字符串开头的所有非数字字符。 Also value_counts is faster than groupby().size() . value_counts也比groupby().size()快。

clientcsv.COBERTURA.str.extract('^(\D)+', expand=False).value_counts()

You can create an aux column, with only the first letter.您可以创建一个仅包含第一个字母的 aux 列。

clientesv['new_label'] = clientesv.COBERTURA.str[0]
group_clients = clientesv.groupby('new_label')['COBERTURA'].agg('sum').reset_index()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM