【问题标题】:How to iterate over a nested field in another column to create a new column based off another value?如何遍历另一列中的嵌套字段以基于另一个值创建新列?
【发布时间】:2019-06-11 17:47:35
【问题描述】:

我在 df 中有一个列,它嵌套在一个列表中的 json 中,如下所示:

col1     nested-filed
1        [{nested_data}]

嵌套字段中的数据如下所示:

[{'field': 1, 'timestamp': 1511404149332, 'changed-timestamp': 0, 'identities': [{'type': 'leadid', 'value': '123-456', 'timestamp': 1488815181110}, {'type': 'ID', 'value': '0987654321', 'timestamp': 1489691285116}, {'type': 'EMAIL', 'value': '1@1', 'timestamp': 1488815179334, 'is': True}]}]

我想按行拉出emailID,所以新的df 看起来像这样:

col1     nested-filed          email           ID
1        [{nested_data}]       1@1.com         0987654321

我该怎么做?我在数据框中有数百万行需要提取这些字段。

【问题讨论】:

    标签: json python-3.x pandas dataframe nested


    【解决方案1】:

    你可以试试这个 -

    import ast
    df.nested_filed = df.nested_filed.apply(lambda x: ast.literal_eval(x))
    
    # Store in a new column named email
    df['email'] = df.nested_filed.apply(lambda x: x[2]['value'])
    
    # Store in a new column named ID
    df['ID'] = df.nested_filed.apply(lambda x: x[1]['value'])
    

    【讨论】:

    • 当我运行df.nested_filed 行时,我收到错误SyntaxError: can't assign to operator。当我更改df['nested_filed'] 时,我收到错误ValueError: malformed node or string:
    • 提供可复现的代码,让我可以从头检查
    • df['nested-field'] = df['nested-field'].apply(lambda x: ast.literal_eval(x)) 这是导致ValueError: malformed node or string: 的行
    • @RustyShackleford - json 似乎无效
    • @jezrael 这就是 API 向我提供数据的方式,无论如何我可以将其转换为有效的 json 吗?
    猜你喜欢
    • 2020-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-17
    • 2021-09-25
    相关资源
    最近更新 更多