DataFrame が与えられた場合、各行のゼロの数を計算したいと思います。Pandas で計算するにはどうすればよいでしょうか?
これは私が現在行っていることです。これはゼロのインデックスを返します
def is_blank(x):
return x == 0
indexer = train_df.applymap(is_blank)
ベストアンサー1
ブール比較を使用してブール 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
上記を詳しく説明すると、
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
編集
david が指摘したように、呼び出し時に型がアップキャストされるため、astype
to は不要であり、次のように簡略化されます。int
Boolean
int
sum
(df == 0).sum(axis=1)