首页 > 解决方案 > 如何将每列只有 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

标签: pythonjsonpandas

解决方案


您可以使用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在第一次更轻松地解析它。


推荐阅读