python - 基于 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
谢谢你的帮助
解决方案
要保存多个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.json
和B.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
--------------------------------------------------------------------------------
推荐阅读
- c# - 参考如何在 Visual Studio 2017 中工作?
- elasticsearch - Elasticsearch - 如何使用嵌套字段过滤数据
- ios - 如何知道检测到的节点在 ARKit 中是垂直的还是水平的?
- ruby-on-rails - 在 Rails cookie 和不同的控制器中存储/检索值
- r - 如何在R中的函数中使用列表作为参数
- android - 无法更改 Gradle 的 distributionUrl
- c# - 如果在目标 power-shell 脚本中创建新进程,VSTS Build Task 会挂起
- java - 法语符号不显示在控制台 Windows 中
- vba - 实时数据单元格拆分和添加
- php - 在回显查询字符串时获取错误的变量名