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
CodePudding user response:
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