【问题标题】:Merge 2 relational dataframes to nested JSON / dataframe将 2 个关系数据帧合并到嵌套的 JSON / 数据帧
【发布时间】:2018-09-07 08:19:36
【问题描述】:

我在使用 pandas 加入数据框时遇到了另一个问题。我想将一个完整的数据帧合并到另一个数据帧的列/字段中,其中 DF2 的外键字段与 DF1 的唯一键匹配。

输入数据是 2 个 CSV 文件,大致如下:

CSV 1 / DF 1:

cid;name;surname;address
1;Mueller;Hans;42553
2;Meier;Peter;42873
3;Schmidt;Micha;42567
4;Pauli;Ulli;98790
5;Dick;Franz;45632

CSV 2 / DF 1:

OID;ticketid;XID;message
1;9;1;fgsgfs
2;8;2;gdfg
3;7;3;gfsfgfg
4;6;4;fgsfdgfd
5;5;5;dgsgd
6;4;5;dfgsgdf
7;3;1;dfgdhfd
8;2;2;dfdghgdh

我希望 DF2 的每一行(XID 与 DF1 的 cid 匹配)作为 DF1 中的单个字段。我的最终目标是将上述输入文件转换为嵌套的 JSON 格式。

编辑 1:

类似这样的:

    [
      {
        "cid": 1,
        "name": "Mueller",
        "surname": "Hans",
        "address": 42553,
        "ticket" :[{
                   "OID": 1,
                   "ticketid": 9,
                   "XID": 1,
                   "message": "fgsgfs"
                   }]
      },
    ...]

编辑 2:

一些进一步的想法:是否可以为数据帧 2 中的每一行创建一个字典,然后将此字典附加到数据帧 1 中的新列,其中字典的某些值(xid)与行中的唯一 id 匹配(cid) ?

我脑海中的一些伪代码:

Add new column "ticket" in DF1
Iterate over rows in DF2:
    row to dictionary
    iterate over DF1
        find row where cid = dict.XID
            append dictionary to field in "ticket"
convert DF1 to JSON

也可以接受非 Python 解决方案。

【问题讨论】:

  • 你能添加一个预期结果的样本吗?
  • 我的最终目标基本上是一个嵌套的 json,其中来自 CSV 2 的数据是子对象。我将很快更新一个示例输出。
  • 您的示例输出中不应该有 2 张票 (XID = 1) 吗?
  • 你是对的。我会改变这一点。我分别创建了示例输入/输出。

标签: python json pandas csv dataframe


【解决方案1】:

不确定您期望的输出,但请查看merge

df1.merge(df2, left_on="cid", right_on="XID", how="left")

[根据预期输出进行编辑]

可能是这样的:

(
    df1.merge(
        df2.groupby("XID").apply(lambda g: g.to_dict(orient="records")).reset_index(name="ticket"), 
        how="left", left_on="cid", right_on="XID")
    .drop(["XID"], axis=1)
    .to_json(orient="records")
)

【讨论】:

  • 感谢您的回答。但是,这并没有给我想要的输出。我知道基本的合并和加入,但我需要在输出数据框的列中包含完整的 df2。
猜你喜欢
  • 2019-04-11
  • 1970-01-01
  • 2018-10-11
  • 1970-01-01
  • 1970-01-01
  • 2016-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多