首页 > 解决方案 > python - 我需要使用 sum() 用 for 循环填充数据框

问题描述

如何?

我需要用 sum 函数返回的数据来完成我的数据框。

所以,我有这个代码来创建我的数据框:

columns = ['hom_doloso', 'lesao_corp_morte', 'latrocinio',
       'hom_por_interv_policial', 'tentat_hom', 'lesao_corp_dolosa', 'estupro',
       'hom_culposo', 'lesao_corp_culposa', 'roubo_comercio',
       'roubo_residencia', 'roubo_veiculo', 'roubo_carga', 'roubo_transeunte',
       'roubo_em_coletivo', 'roubo_banco', 'roubo_cx_eletronico',
       'roubo_celular', 'roubo_conducao_saque', 'roubo_apos_saque',
       'roubo_bicicleta', 'outros_roubos', 'total_roubos', 'furto_veiculos',
       'furto_transeunte', 'furto_coletivo', 'furto_celular',
       'furto_bicicleta', 'outros_furtos', 'sequestro',
       'extorsao', 'sequestro_relampago', 'estelionato', 'apreensao_drogas',
       'posse_drogas', 'trafico_drogas', 'apreensao_drogas_sem_autor', 'ameaca']

index = [1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
       2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012,
       2013, 2014, 2015, 2016, 2017, 2018, 2019] 
new_df = pd.DataFrame(index=index, columns=columns) 

然后我需要用聚合函数填充此 DataFrame 中的每一列,例如:

new_df.hom_doloso = df_clean.groupby('vano').hom_doloso.sum()

返回:

new_df.head()
      hom_doloso   lesao_corp_morte   latrocinio  ...
1991    7518              NaN             NaN
1992    7635              NaN             NaN
1993    7720              NaN             NaN
1994    8408              NaN             NaN

上面的代码只完成了数据框的一列,我真的不想写所有这些列名,所以我尝试使用 For Loop,但我不能这样做

for column_name in columns:
  new_df.column_name = df_clean.groupby('vano').column_name.sum()

此 for 中的 column_name 需要替换为每个列名

df_clean:df_clean.shape: (344, 56)

df_clean.head()```
      vano    hom_doloso   lesao_corp_morte   latrocinio  ...
0     1991    7518              0.0             18
1     1992    7635              0.0             17
2     1993    7720              0.0             16
3     1994    8408              0.0             15

new_df 只会在名为 columns 的变量中包含这些列, df_clean 也有。

我需要按“vano”分组以返回每列的总和。

有没有办法做到这一点?

标签: pythonpandasdataframe

解决方案


不需要循环。让我们尝试这样的事情:

np.random.seed(123)
df = pd.DataFrame(np.random.randint(0,100,(5,5)), columns=[*'ABCDE'])
df['grp'] = ['A','A','A','B','B']
print(df)

输出:

    A   B   C   D   E grp
0  66  92  98  17  83   A
1  57  86  97  96  47   A
2  73  32  46  96  25   A
3  83  78  36  96  80   B
4  68  49  55  67   2   B

现在,让我们重塑数据框堆栈我们想要求和的所有列,在我们不想求和的所有列上设置索引,并使用 groupby 和级别。最后,取消堆叠最内层以获取列。

df.set_index('grp').stack().groupby(level=[0,1]).sum().unstack()

或者

df.set_index('grp').stack().sum(level=[0,1]).unstack().reset_index()

输出:

  grp    A    B    C    D    E
0   A  196  210  241  209  155
1   B  151  127   91  163   82

推荐阅读