简体   繁体   中英

How I can count elements of a column?

Hi I am wondering how I can count elements of each row?

I have the following column:

Column
(‘a’, ‘b’),(‘a’, ‘c’),(‘b’, ‘c’)
(‘g’, ‘h’),(‘a’, ‘c’),(‘a’, ‘b’)

I wanna count how many of the above pair exist in the data set!

Output:
(‘a’, ‘b’)  2
(‘a’, ‘c’). 2
(‘b’, ‘c’).  1
(‘g’, ‘h’).  1

Use findall to extract tuple and explode to separate them. Finally, use value_counts to count occurrences:

>>> df.Column.str.findall(r'(\([^()]+\))').explode().value_counts()

(‘a’, ‘b’)    2
(‘a’, ‘c’)    2
(‘b’, ‘c’)    1
(‘g’, ‘h’)    1
Name: Column, dtype: int64

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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