Siavash
Siavash

Reputation: 190

Counting the numbers in each row using python

I have a pandas data frame:

a   b   c   d
./. 0/1 ./. 0/1
0/1 1/1 0/0 1/1
0/1 1/1 ./. 1/1

I want to know, how can I get the total number of "0" and "1" in each row same as:

a   b   c   d   C0  C1
./. 0/1 ./. 0/1 2   2
0/1 1/1 0/0 1/1 3   5
0/1 1/1 ./. 1/1 1   5

Upvotes: 2

Views: 95

Answers (1)

Shubham Sharma
Shubham Sharma

Reputation: 71689

Let's .stack the dataframe to reshape, then use .str.extractall to extract all capture groups in the regex pattern as columns, finally use .notna + .sum on level=0 to count the number of 0's and 1's:

df[['c0', 'c1']] = df.stack().str.extractall(r'(0)|(1)').notna().sum(level=0)

     a    b    c    d  c0  c1
0  ./.  0/1  ./.  0/1   2   2
1  0/1  1/1  0/0  1/1   3   5
2  0/1  1/1  ./.  1/1   1   5

Upvotes: 4

Related Questions