熊猫groupby选择条件下的细胞

时间:2019-07-20 19:06:14

标签: python pandas group-by

我想对数据框进行分组,然后计算每组中虚拟事件的平均值。

df3 = pd.DataFrame({'Number':['001','001','001','002','002','002','002'],
                   'name':['peter','chris','meg','albert','cathrine','leo','leo'],
                   'dummy':[0,1,1,0,0,1,1]})

我可以使用以下代码计算每组中唯一事件的平均发生次数(基于名称):

test=df3.groupby('Number')
test_1 = []
for name, group in test:
    x= len(group.name.unique())
    test_1.append(x)
pd.Series(test_1).mean()

现在,我想计算假名在一个组中平均等于1的频率,

  

因此,在此示例中,计算将为(2 + 1)/ 2 = 1.5。   其中(第1组(2)的唯一虚拟计数+第2组(1)的唯一虚拟计数)/除以组数(2)=每组平均1.5个唯一虚拟计数

请注意,如果组中没有虚拟对象,则分母中的组数仍应增加1

如果我没有明确表达任务,请发表评论!

2 个答案:

答案 0 :(得分:0)

s = df3.groupby('Number').agg({"name":["nunique"], "dummy": ["sum"]})
sum(s["name"]["nunique"]/s["dummy"]["sum"])

如果我正确理解您的意思

在更优雅的实现中-

def my_func(x):
     n = x['name'].nunique()
     s = x['dummy'].sum()
     return n/s

df3.groupby('Number').apply(my_func).mean()

修改

我终于以为看到问者提出的建议解决方案后我就明白了-

df4 = df3[df3.dummy == 1]

df4.groupby('Number').apply(lambda x: x["name"].nunique()).sum()/df4.Number.nunique()

答案 1 :(得分:0)

好吧,尽管有一些解决方法,我还是找到了我问题的答案:

df3 = pd.DataFrame({'Number':['001','001','001','002','002','002','002'],
                   'name':['peter','chris','meg','albert','cathrine','leo','leo'],
                   'dummy':[0,1,0,0,0,1,1]})

df4=df3.loc[df3.dummy.isin(['1'])] #creating new dataframe with only the rows where dummy = 1

test=df4.groupby('Number') # group it by the number column

test_1 = []
for name, group in test:
    x= len(group.name.unique()) #take  only the unique names in each group
    test_1.append(x)
pd.Series(test_1).sum()/len(test) # divide value count by number of groups