dataframe - 如何在熊猫数据框中填充 0?
问题描述
我想在那些不存在的集群名称中填充 0。正如预期的输出一样,我在最后一行添加了 0,因为我在数据框中没有找到任何结果。 输入:
到目前为止我已经尝试过
#I have made clusters according to the requirement and making sum of it
# output of this code is given above
d_inv = {x: k for k, v in dict1.items() for x in v}
df = df['PII Count'].groupby(df['PII'].map(d_inv)).sum() \
.rename_axis('Cluster names') \
.reset_index(name='Total count')
print(df)
解决方案
如果顺序无关紧要,请使用重新索引并使用以下键dict1
:
(df['PII Count'].groupby(df['PII'].map(d_inv)).sum().rename_axis('Cluster names')
.reindex(dict1.keys(),fill_value=0)
.reset_index(name='Total count'))
Cluster names Total count
0 Personal Info 270
1 Health Info 0
2 Network Info 94
3 Others Info 59
4 Finance Info 1
如果订单很重要:
m = df['PII'].map(d_inv)
out = df['PII Count'].groupby(m).sum()
out = (out.reindex(out.index.union(set(dict1.keys()).difference(m),sort=False),
fill_value=0)
.rename_axis('Cluster names')
.reset_index(name='Total count'))
print(out)
Cluster names Total count
0 Finance Info 1
1 Network Info 94
2 Others Info 59
3 Personal Info 270
4 Health Info 0
推荐阅读
- android - 为什么jw播放器不会全屏?
- android - 如何解决版本冲突的依赖问题?
- sql - 检查任何三个连续交易是否超过指定金额
- ruby - 我正在使用 MediaRecorder API 录制语音,为什么块小于实际大小?
- python - Keras mode.fit - 为什么每次新运行都会产生不同的结果(准确度和损失)?
- c - 为什么在进行远程过程调用时,UDP 优于 TCP?
- google-cloud-platform - 如何在现有的谷歌云虚拟机实例上启用嵌套虚拟化?
- sustainsys-saml2 - 带有 Owin 的 SAML2 - 无法进行身份验证
- java - Maven:如何在 Web 应用程序构建期间在 lib 文件夹中添加所有 jar 文件
- javascript - 使用 lodash _.forEach 循环遍历动态数组