本文介绍了Python Pandas:在数据框的每一行中计算特定值的频率吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框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并计算每行列(out1,out2,out3)中0和1的数量.因此预期结果将是:

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

我有用于计算1s数量的代码,但是我不知道如何计算0s的数量.

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)

有人可以帮忙吗?

推荐答案

您可以为每个条件调用sum1条件很简单,只需在axis=1上直接输入sum,第二个您就可以将df与0值进行比较,然后像以前一样调用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

这篇关于Python Pandas:在数据框的每一行中计算特定值的频率吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 17:20