python - 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”分组以返回每列的总和。
有没有办法做到这一点?
解决方案
不需要循环。让我们尝试这样的事情:
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
推荐阅读
- twitter - 删除 Twitter webhook 真的需要我拥有所有相关的消费者凭据吗?
- javascript - 事件监听器以防止在触摸鼠标水平滚动/后退按钮上刷新 javascript
- java - 变量的继承值为 0
- python - 为什么从模型生成的边界框保存的图像与原始图像相比分辨率要低得多
- r - 使用 R Shiny 创建问卷
- c++ - 如何通过代码中的麦克风在语音识别中使用pocketsphinx
- angular - 如何使用按钮触发 Facebook Messenger
- javascript - 使用wheelnav.js 如何将我的轮子连接到复制滑块
- excel - VBA Open方法仅在崩溃后才有效
- angular - Angular Reactive Form - 选项下拉菜单