怎么用Pandas DataFrame统计每一行0值的个数?

这里有两种方法:

1. 首先可以通过(df == 0).astype(int).sum(axis=1),举个例子:

in[34]:df = pd.DataFrame({'a':[1,0,0,1,3],'b':[0,0,1,0,1],'c':[0,0,0,0,0]})
in[35]:df
Out[35]: 
   a  b  c
0  1  0  0
1  0  0  0
2  0  1  0
3  1  0  0
4  3  1  0


in[36]:(df == 0).astype(int).sum(axis=1)

Out[36]: 

0    2
1    3
2    2
3    2
4    1

dtype: int64

拆开来看如下:

in[37]: df == 0
Out[37]: 
       a      b     c
0  False   True  True
1   True   True  True
2   True  False  True
3  False   True  True

4  False  False  True

in[38]:(df == 0).astype(int)
Out[38]: 
   a  b  c
0  0  1  1
1  1  1  1
2  1  0  1
3  0  1  1

4  0  0  1

或者更加省略一些是:(df == 0).sum(axis=1)

命令中转化成int不是特别必要,因为boolean类型在进行sum操作时会自动变为int类型。

2. 另一种方法是通过使用apply()和value_counts():

in[40]: df.apply(lambda x : x.value_counts().get(0,0),axis=1)

Out[40]: 
0    2
1    3
2    2
3    2
4    1
dtype: int64

猜你喜欢

转载自blog.csdn.net/kkkkkiko/article/details/80845859