给定一个DataFrame,我想计算每行的零数.如何用Pandas计算它?
这是我现在所做的,这会返回零的索引
def is_blank(x):
return x == 0
indexer = train_df.applymap(is_blank)
Run Code Online (Sandbox Code Playgroud)
EdC*_*ica 35
使用一个布尔比较,它将产生一个布尔df,我们可以将其转换为int,True变为1,False变为0然后调用count
并传递param axis=1
以逐行计数:
In [56]:
df = pd.DataFrame({'a':[1,0,0,1,3], 'b':[0,0,1,0,1], 'c':[0,0,0,0,0]})
df
Out[56]:
a b c
0 1 0 0
1 0 0 0
2 0 1 0
3 1 0 0
4 3 1 0
In [64]:
(df == 0).astype(int).sum(axis=1)
Out[64]:
0 2
1 3
2 2
3 2
4 1
dtype: int64
Run Code Online (Sandbox Code Playgroud)
突破以上:
In [65]:
(df == 0)
Out[65]:
a b c
0 False True True
1 True True True
2 True False True
3 False True True
4 False False True
In [66]:
(df == 0).astype(int)
Out[66]:
a b c
0 0 1 1
1 1 1 1
2 1 0 1
3 0 1 1
4 0 0 1
Run Code Online (Sandbox Code Playgroud)
编辑
由大卫指出astype
来int
是不必要的,因为Boolean
类型会被upcasted到int
时调用sum
所以这简化为:
(df == 0).sum(axis=1)
Run Code Online (Sandbox Code Playgroud)
小智 32
您可以使用 python pandas 的以下函数计算每列的零。它可能有助于需要计算每列特定值的人
df.isin([0]).sum()
Run Code Online (Sandbox Code Playgroud)
这里 df 是数据帧,我们要计数的值为 0
这是使用apply()
and 的另一种解决方案value_counts()
。
df = pd.DataFrame({'a':[1,0,0,1,3], 'b':[0,0,1,0,1], 'c':[0,0,0,0,0]})
df.apply( lambda s : s.value_counts().get(key=0,default=0), axis=1)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
26845 次 |
最近记录: |