如何对行进行分组,在一列中计数,而另一列中相加?

问题描述 投票:1回答:3

我想对一个csv文件的行进行分组,在一列中计数,在另一列中添加。

例如,以下内容我想对Commune上的行进行分组,以使winner的列具有计数,而列Swing的列具有总数

Commune Winner Swing longitude latitude turnout
Paris   PAM    1     12.323    12.093   0.3242
Paris   PJD    0     12.323    12.093   0.1233
Paris   PAM    1     12.323    12.093   0.534
Paris   UDF    1     12.323    12.093   0.65434
Madrid  PAM    0     10.435    -3.093   0.3423
Madrid  PAM    1     10.435    -3.093   0.5234
Madrid  PJD    0     10.435    -3.093   0.235

如何对行进行分组,一列中有一列,另一列中有和?

Commune PAM    PJD    UDF    Swing
Paris   3      1      1      3
Madrid  2      1      0      1

到目前为止,我尝试过尝试:

g = df.groupby('Commune').Winner
pd.concat([g.apply(list), g.count()], axis=1, keys=['members', 'number'])

但它返回:

    members number
Commune     
Paris   [PAM, PJD, PAM, UDF] 4
Madrid  [PAM, PAM, UDF] 3
python python-3.x pandas pandas-groupby
3个回答
2
投票

这应该做:

pd.pivot_table(df, values='Swing', index='Commune', columns='Winner', aggfunc='count').fillna(0).join(df.groupby('Commune')['Swing'].sum())

#         PAM  PJD  UDF  Swing
#Commune                      
#Madrid   2.0  1.0  0.0      1
#Paris    2.0  1.0  1.0      3

2
投票

使用crosstab并用crosstab添加新列并聚合DataFrame.join

DataFrame.join

但是如果需要行数:

sum

或:

df = pd.crosstab(df['Commune'], df['Winner']).join(df.groupby('Commune')['Swing'].sum())
print (df)
         PAM  PJD  UDF  Swing
Commune                      
Madrid     2    1    0      1
Paris      2    1    1      3

df1 = pd.crosstab(df['Commune'], df['Winner'], margins=True, margins_name='Total').iloc[:-1]

编辑:

如果每个组的所有值以及对于df = pd.crosstab(df['Commune'], df['Winner']).assign(Total= lambda x: x.sum(axis=1)) 的所有值都使用诸如print (df1) Winner PAM PJD UDF Total Commune Madrid 2 1 0 3 Paris 2 1 1 4 first ...的其他聚合函数,则[如果有其他列,则可以使用turnout进行聚合

mean

如果可能想要所有没有sum的列中的df1 = (df.groupby('Commune') .agg({'Swing':'sum', 'longitude':'first','latitude':'first','turnout':'mean'})) print (df1) Swing longitude latitude turnout Commune Madrid 1 10.435 -3.093 0.36690 Paris 3 12.323 12.093 0.40896 df = pd.crosstab(df['Commune'], df['Winner']).join(df1) print (df) PAM PJD UDF Swing longitude latitude turnout Commune Madrid 2 1 0 1 10.435 -3.093 0.36690 Paris 2 1 1 3 12.323 12.093 0.40896 可以动态创建字典:

mean

0
投票

这就是我的做法。

Swing
© www.soinside.com 2019 - 2024. All rights reserved.