【问题标题】:separate multiple values from a key into their own key/value pairs将一个键中的多个值分离为它们自己的键/值对
【发布时间】:2021-11-01 20:11:47
【问题描述】:

如果我们有以下字典列表:

df=[{'answers': ['Yes', 'No'], 'question': 'status', 'type': 'string'}]

如何将上面的列表分成两个字典,答案键只有一个值:

df=[{'answers': ['Yes'], 'question': 'status', 'type': 'string'}, {'answers': ['No'], 'question': '状态','类型':'字符串'}]

任何指导将不胜感激。谢谢

【问题讨论】:

    标签: python dictionary data-processing


    【解决方案1】:

    我认为您的意思是您使用 DataFrames(因此您的变量名称为 df)。在那种情况下,pandas 已经为这个特定用例提供了一个功能:explode:

    import pandas as pd
    df = pd.DataFrame([{'answers': ['Yes', 'No'], 'question': 'status', 'type': 'string'}])
    print(df.explode('answers'))
    

    输出:

      answers question    type
    0     Yes   status  string
    0      No   status  string
    

    编辑:您可以使用to_dict 轻松返回字典表单:

    df = df.explode('answers')
    print(df.to_dict(orient='records'))
    

    输出:

    [{'answers': 'Yes', 'question': 'status', 'type': 'string'}, {'answers': 'No', 'question': 'status', 'type': 'string'}]
    

    【讨论】:

      【解决方案2】:

      你可以试试这个:

        import copy 
          df=[{'answers': ['Yes', 'No'], 'question': 'status', 'type': 'string'}]
          df2=copy.deepcopy(df)
          content = df[0]
          for x,y in content.items():
            if (len(y) > 1) and isinstance(y,list):
              df[0][x]=y[0]
              df2[0][x]=y[1]
          # print(df)
          print(df2)
          print(df)
      

      但这仅适用于 2 个列表而不是更多

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-08
        • 1970-01-01
        • 2023-04-10
        • 1970-01-01
        • 2019-03-30
        相关资源
        最近更新 更多