問題描述
我有一個(gè)數(shù)據(jù)框 df:
I have a dataframe df:
domain country out1 out2 out3
oranjeslag.nl NL 1 0 NaN
pietervaartjes.nl NL 1 1 0
andreaputting.com.au AU NaN 1 0
michaelcardillo.com US 0 0 NaN
我想定義兩列 sum_0 和 sum_1 并計(jì)算每行列 (out1,out2,out3) 中 0 和 1 的數(shù)量.所以預(yù)期的結(jié)果是:
I would like to define two columns sum_0 and sum_1 and count the number of 0s and 1s in columns (out1,out2,out3),per row. So expected results would be:
domain country out1 out2 out3 sum_0 sum_1
oranjeslag.nl NL 1 0 NaN 1 1
pietervaartjes.nl NL 1 1 0 1 2
andreaputting.com.au AU NaN 1 0 1 1
michaelcardillo.com US 0 0 NaN 2 0
我有這個(gè)計(jì)算1個(gè)數(shù)的代碼,但我不知道如何計(jì)算0個(gè)數(shù).
I have this code for counting the number of 1s, but I do not know how to count the number of 0s.
df['sum_1'] = df[['out_1','out_2','out_3']].sum(axis=1)
有人可以幫忙嗎?
推薦答案
你可以為每個(gè)條件調(diào)用sum
,1
條件很簡單,只是一個(gè)直接的axis=1
上的 sum,第二次您可以將 df 與 0
值進(jìn)行比較,然后像以前一樣調(diào)用 sum
:
You can call sum
for each condition, the 1
condition is simple just a straight sum
on axis=1
, for the second you can compare the df against 0
value and then call sum
as before:
In [102]:
df['sum_1'] = df[['out1','out2','out3']].sum(axis=1)
df['sum_0'] = (df[['out1','out2','out3']] == 0).sum(axis=1)
df
Out[102]:
domain country out1 out2 out3 sum_0 sum_1
0 oranjeslag.nl NL 1 0 NaN 1 1
1 pietervaartjes.nl NL 1 1 0 1 2
2 andreaputting.com.au AU NaN 1 0 1 1
3 michaelcardillo.com US 0 0 NaN 2 0
這篇關(guān)于Python Pandas:計(jì)算每行數(shù)據(jù)幀中特定值的頻率?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!