python - 如何将每列只有 1 个非空条目的 pandas 数据框中的多行合并为一行?
问题描述
我正在使用 json_normalize 来解析 pandas 列的 json 条目。但是,作为输出,我得到一个包含多行的数据框,每行只有一个非空条目。我想将所有这些行合并到 pandas 中的一行。
currency custom.gt custom.eq price.gt price.lt
0 NaN 4.0 NaN NaN NaN
1 NaN NaN NaN 999.0 NaN
2 NaN NaN NaN NaN 199000.0
3 NaN NaN other NaN NaN
4 USD NaN NaN NaN NaN
解决方案
您可以使用ffill(前向填充)和bfill(回填),它们是在 pandas 中填充 NA 值的方法。
# fill NA values
# option 1:
df = df.ffill().bfill()
# option 2:
df = df.fillna(method='ffill').fillna(method='bfill')
print(df)
currency custom.gt custom.eq price.gt price.lt
0 USD 4.0 other 999.0 199000.0
1 USD 4.0 other 999.0 199000.0
2 USD 4.0 other 999.0 199000.0
3 USD 4.0 other 999.0 199000.0
4 USD 4.0 other 999.0 199000.0
然后,您可以使用drop_duplicates删除重复的行并保留第一个:
df = df.drop_duplicates(keep='first')
print(df)
currency custom.gt custom.eq price.gt price.lt
0 USD 4.0 other 999.0 199000.0
根据您必须重复该任务的次数,我可能还会查看 JSON 文件的结构,以查看使用字典理解是否有助于清理内容,以便json_normalize
在第一次更轻松地解析它。
推荐阅读
- latex - 我可以将文件附加/嵌入到 Latex 文档中并将其超链接到单词以进行保存吗?
- python - 如何在 vscode 中使用 pytest 测试文件夹中的文件?
- python - 多年来迭代以将不同的组值绘制为熊猫中的条形图
- python - 取平均值时向前传播值
- django - Django Recaptcha 返回分配错误
- javascript - HTML - 将 json 转换为表格
- sql - 创建一个接受 id 列表的函数?
- javascript - 如何将 express.js 服务器部署到 Netlify
- javascript - 如果使用数组解构,则需要不同的导入
- google-maps - 如何在 kotlin 的谷歌地图中跟踪步行