【问题标题】:Split nested column into new columns将嵌套列拆分为新列
【发布时间】:2021-08-13 01:46:29
【问题描述】:

我的数据框有一个嵌套列 (people_info),其中包含如下示例所示的单元格。

[{"institution":"some_institution","startMonth":1,"startYear":2563,"course":"any","id":1111,"formation":"any","endMonth" :12,"endYear":2556,"status":"complete"}]

据我所知,这可以使用字典/json 概念来解决。

考虑到这个嵌套单元格的每个键都是具有各自值的新列,我正在尝试将此列拆分为新列。

我尝试了 json_normalize,但我收到了这个错误:“AttributeError: 'str' object has no attribute 'values'”

我试图在字典中转换这些单元格,但我从来没有能够让 python 理解“机构”是一个键,而“some_institution”是这个创建的字典中的一个值。似乎 python 将整个单元格理解为一个字符串。

你能帮帮我吗?如果我不清楚,请告诉我。谢了!

【问题讨论】:

    标签: python json pandas dictionary nested


    【解决方案1】:

    也许这会有所帮助。

    将熊猫导入为 pd

    数据 = [{"机构":"some_institution", “开始月份”:1, “开始年”:2563, “课程”:“任何”, “身份证”:1111, “形成”:“任何”, “月底”:12, “年终”:2556, “状态”:“完成”}]

    l = next(数据中的项目)

    df = pd.DataFrame(l, index=[0])

    df

    【讨论】:

    • 感谢您的帮助!但它不起作用,因为“[{”是此 DataFrame 中单元格文本的一部分。所以这个函数不能正常工作,因为python不理解“数据”是一个字典列表。
    【解决方案2】:

    IIUC,以下应该可以工作:

    输入

    df = pd.DataFrame({'col1':[1], 'col2':2, 'nested_column':'[{"institution":"some_institution","startMonth":1,"startYear":2563,"course":"any","id":1111,"formation":"any","endMonth":12,"endYear":2556,"status":"complete"}]'})
    
    df
    
      col1  col2    nested_column
    0    1     2    [{"institution":"some_institution","startMonth...
    

    流程

    import json
    df['nested_column_dict'] = df['nested_column'].transform(lambda x : json.loads(x)[0] if x is not np.nan else {})
    df = pd.concat([df, pd.DataFrame.from_records(df['nested_column_dict'])], axis=1)
    df.drop('nested_column_dict', axis=1, inplace=True)
    

    输出

     df
    
     col1   col2    nested_column                                           institution startMonth  startYear   course    id    formation   endMonth    endYear   status
    0   1      2    [{"institution":"some_institution","startMonth...   some_institution         1      2563       any  1111          any         12       2556 complete
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-18
      • 2012-10-20
      • 1970-01-01
      • 2017-08-24
      • 1970-01-01
      相关资源
      最近更新 更多