使用 python 计算每行中的数字

Counting the numbers in each row using python

我有一个 pandas 数据框:

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

我想知道,我怎样才能得到每一行中“0”和“1”的总数:

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

让我们.stack the dataframe to reshape, then use .str.extractall to extract all capture groups in the regex pattern as columns, finally use .notna + .sumlevel=0上计算0's1'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