在大熊猫中混合聚集和分组

时间:2019-11-19 10:44:47

标签: python pandas pandas-groupby

我拥有的是一个名为“报告”的数据集,其中包含交付驱动程序的详细信息。 “通过”表示他们按时交货,而“失败”表示他们没有按时交货

Name|Outcome
A   |Pass
B   |Fail
C   |Pass
D   |Pass
A   |Fail
C   |Pass

我想要的

Name|Pass|Fail|Total
A   |1   |1   |2
B   |0   |1   |1
C   |2   |0   |2
D   |1   |0   |1

我尝试过:

report.groupby(['Name','outcome']).agg(['count'])

但是它没有给我所需的输出

非常感谢

4 个答案:

答案 0 :(得分:6)

heremargins=Truemargins_name参数一起使用:

print (pd.crosstab(df['Name'], df['Outcome'], margins=True, margins_name='Total'))
Outcome  Fail  Pass  Total
Name                      
A           1     1      2
B           1     0      1
C           0     2      2
D           0     1      1
Total       2     4      6

然后删除位置为crosstab的最后一行:

df = pd.crosstab(df['Name'], df['Outcome'], margins=True, margins_name='Total').iloc[:-1]
print (df)
Outcome  Fail  Pass  Total
Name                      
A           1     1      2
B           1     0      1
C           0     2      2
D           0     1      1

答案 1 :(得分:5)

这是pd.crosstabsum超过axis=1

df = pd.crosstab(df['Name'], df['Outcome'])
df['Total'] = df[['Fail', 'Pass']].sum(axis=1)
Outcome  Fail  Pass  Total
Name                      
A           1     1      2
B           1     0      1
C           0     2      2
D           0     1      1

或者要删除列轴名称,我们使用rename_axis

df = pd.crosstab(df['Name'], df['Outcome']).reset_index().rename_axis(None, axis='columns')
df['Total'] = df[['Fail', 'Pass']].sum(axis=1)
  Name  Fail  Pass  Total
0    A     1     1      2
1    B     1     0      1
2    C     0     2      2
3    D     0     1      1

答案 2 :(得分:1)

In [1]: from io import StringIO

In [2]: df_string = '''Name|Outcome^M
   ...: A   |Pass^M
   ...: B   |Fail^M
   ...: C   |Pass^M
   ...: D   |Pass^M
   ...: A   |Fail^M
   ...: C   |Pass'''


In [3]: report = pd.read_csv(StringIO(df_string), sep='|')

In [4]: report.assign(count=1).groupby(["Name", "Outcome"])["count"].sum().unstack().assign(Total=lambda df: df.sum(axis=1))
Out[4]:
Outcome  Fail  Pass  Total
Name
A         1.0   1.0    2.0
B         1.0   NaN    1.0
C         NaN   2.0    2.0
D         NaN   1.0    1.0

现在您可以使用fillna(0)方法填充NAs值

答案 3 :(得分:0)

使用RDD[SparseVector]pandas.dummies的一种方法:

groupby

输出:

report = pd.get_dummies(df1, columns=['outcome']).groupby(['name'], as_index=False).sum().rename(columns={"outcome_Fail":"Fail", "outcome_Pass":"Pass"})

report["Total"] = report["Pass"] + report["Fail"]

print(report)