Python Pandas:计算每行数据帧中特定值的频率?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33823091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python Pandas: Counting the frequency of a specific value in each row of dataframe?
提问by UserYmY
I have a dataframe df:
我有一个数据框 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
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:
我想定义两列 sum_0 和 sum_1 并计算每行列 (out1,out2,out3) 中 0 和 1 的数量。所以预期的结果是:
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
I have this code for counting the number of 1s, but I do not know how to count the number of 0s.
我有这个用于计算 1 数量的代码,但我不知道如何计算 0 的数量。
df['sum_1'] = df[['out_1','out_2','out_3']].sum(axis=1)
Can anybody help?
有人可以帮忙吗?
回答by EdChum
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:
您可以调用sum
每个条件,1
条件很简单,只是直接sum
在axis=1
,第二个您可以将 df 与0
值进行比较,然后sum
像以前一样调用:
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
回答by AntonyBrd
I would do :
我会做 :
df["sum_0"] = df.apply(lambda row: sum(row[0:3]==0) ,axis=1)