首页 > 解决方案 > 基于 Python Panda 的拆分和分组 json 行文件

问题描述

我是 Python 和 Panda 的新手,有一个用例来读取 json 行文件,根据“类别”属性拆分行并将它们写入另一个名为 category.json 的 json 行文件,该文件将由代码创建。

这可以在其他库中完成,但想知道如何在 Panda 中完成。任何帮助表示赞赏

Input input json line file:
{"header": {"category": "A", "type": "type1"}, "payload": {"attr1": "a1","attr2": "a2"}}
{"header": {"category": "A", "type": "type2"}, "payload": {"attr1": "b1","attr2": "b2"}}
{"header": {"category": "B", "type": "type3"}, "payload": {"attr11": "c1","attr22": "c2", "attr33":"c3"}}
{"header": {"category": "B", "type": "type4"}, "payload": {"attr11": "d1","attr22": "d2", "attr33":"d3"}}

需要创建两个文件:A.json 和 B.json 我设法使用以下方法读取文件:

df = pd.read_json('input.json', lines=True)
categories = pd.DataFrame(df.header.values.tolist())['category'].values
print(categories)

以上返回:["A", "A", "B", "B"]

现在我正在考虑阅读此列表并在此处应用 groupby。我的方法是否正确,或者它使简单的事情变得复杂。

在将它们写入类别明智的文件之前,我还需要进行转置。

预期输出:

一个.json

type  attr1  attr2
type1  a1    a2
type2  b1    b2

B.json

type  attr11  attr22  attr33
type3   c1    c2      c3
type4   d1    d2      d3

谢谢你的帮助

标签: pythonpandasdataframe

解决方案


要保存多个json文件,您可以执行以下操作:

df = pd.read_json("input.json", lines=True)

df = pd.concat(
    [df["header"].apply(pd.Series), df["payload"].apply(pd.Series)], axis=1
)

for v, g in df.groupby("category"):
    g = g.drop(columns="category")
    g.to_json("{}.json".format(v))
    print(g)
    print("-" * 80)

印刷:

    type attr1 attr2
0  type1    a1    a2
1  type2    b1    b2
--------------------------------------------------------------------------------
    type attr1 attr2
2  type3    c1    c2
3  type4    d1    d2
--------------------------------------------------------------------------------

并保存A.jsonB.json


编辑:不同的input.json

df = pd.read_json("input.json", lines=True)

df = pd.concat(
    [df["header"].apply(pd.Series), df["payload"].apply(pd.Series)], axis=1
)


for v, g in df.groupby("category"):
    g = g.drop(columns="category")
    g = g.dropna(axis=1, how="all")  # <-- drop columns with all NaNs
    g.to_json("{}.json".format(v))
    print(g)
    print("-" * 80)

印刷:

    type attr1 attr2
0  type1    a1    a2
1  type2    b1    b2
--------------------------------------------------------------------------------
    type attr11 attr22 attr33
2  type3     c1     c2     c3
3  type4     d1     d2     d3
--------------------------------------------------------------------------------

推荐阅读