2017-08-03 77 views
3

我有一个数据帧包含两个变量:IDoutcome。首先尝试groupbyID,然后统计该ID内的outcome的唯一值的数量。Groupby并计算唯一值的数量(Pandas)

df 
ID outcome 
1  yes 
1  yes 
1  yes 
2  no 
2  yes 
2  no 

预期输出:

ID yes no 
1  3  0 
2  1  2 

我的代码df[['PID', 'outcome']].groupby('PID')['outcome'].nunique()给出了独特的价值本身的数量,使得:

ID 
1 2 
2 2 

但我需要的yesno的计数,我怎么能做到这一点?谢谢!

回答

5

pd.crosstab怎么样?

In [1217]: pd.crosstab(df.ID, df.outcome) 
Out[1217]: 
outcome no yes 
ID    
1   0 3 
2   2 1 
+1

我必须找到一个新的**选项2 ** – piRSquared

+0

@piRSquared其他人想出这是可能的只是一个时间问题:p –

+0

怎么样?这很棒! – Kay

1

分组在ID列,然后在outcome列上使用value_counts进行聚合。这会产生一系列的结果,因此您需要使用.to_frame()将其转换回数据框,以便您可以拆除yes/no(即将它们作为列)。然后用零填充空值。

df_total = df.groupby('ID')['outcome'].value_counts().to_frame().unstack(fill_value=0) 
df_total.columns = df_total.columns.droplevel() 
>>> df_total 
outcome no yes 
ID    
1   0 3 
2   2 1 
+0

@piRSquared是的。谢谢。 – Alexander

0

使用​​和pd.concat

df1 = df.set_index('ID') 
pd.concat([df1.outcome.eq('yes').sum(level=0), 
      df1.outcome.ne('yes').sum(level=0)], keys=['yes','no'],axis=1).reset_index() 

输出:

ID yes no 
0 1 3.0 0.0 
1 2 1.0 2.0 
0

最有效的设置,这将防止任何过去,现在和未来的错误,并采取快速矢量化功能优势做(疯狂简单)以下的事情:

df['dummy_yes'] = df.outcome == 'yes' 
df['dummy_no'] = df.outcome == 'no' 

df.groupby('ID').sum() 
+0

您为什么认为其他解决方案会导致过去,现在或将来的错误? –

+0

这是可以用任何语言工作的东西。在尝试做更多pandonic素材时,我有过一些严重和微妙的错误 –

+0

@coldspeed这里是它https://stackoverflow.com/questions/36337012/how-to-get-multiple-conditional-operations-after-a -pandas-groupby –

4

选项2
pd.factorize + np.bincount
这是令人费解的,痛苦......但速度非常快。

fi, ui = pd.factorize(df.ID.values) 
fo, uo = pd.factorize(df.outcome.values) 

n, m = ui.size, uo.size 
pd.DataFrame(
    np.bincount(fi * m + fo, minlength=n * m).reshape(n, m), 
    pd.Index(ui, name='ID'), pd.Index(uo, name='outcome') 
) 

outcome yes no 
ID    
1   3 0 
2   1 2 

选项C

pd.get_dummies(d.ID).T.dot(pd.get_dummies(d.outcome)) 

    no yes 
1 0 3 
2 2 1 

方案四

df.groupby(['ID', 'outcome']).size().unstack(fill_value=0) 
+0

谢谢!你的选择C中的“T”是什么意思? – Kay

+0

这意味着“糟糕”hahaha –

+1

@Kay转置数据帧 – piRSquared