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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:15:36  来源:igfitidea点击:

Python Pandas: Counting the frequency of a specific value in each row of dataframe?

pythonpandassumrow

提问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 sumfor each condition, the 1condition is simple just a straight sumon axis=1, for the second you can compare the df against 0value and then call sumas before:

您可以调用sum每个条件,1条件很简单,只是直接sumaxis=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)