【问题标题】:Convert columns of lists to column of dictionary [duplicate]将列表列转换为字典列[重复]
【发布时间】:2020-11-11 05:24:53
【问题描述】:

在一个大熊猫数据框中,我有三列(fruitvegetablefirst_name)。这些列的值是列表。

从列表中,我想为 DataFrame 的每一行创建一个包含字典列表的新列。

我有三列(fruitvegetablefirst_name),每一行都有列表作为它们的值。

我的数据框的第一行:

df = pd.DataFrame({
 "fruit": [["Apple", "Banana","Pear","Grape","Pineapple"]],
 "vegetable": [["Celery","Onion","Potato","Broccoli","Sprouts"]],
 "first_name": [["Sam", "Beth", "John", "Daisy", "Jane"]]
})

如何将三列转换为一列并使值看起来像这样?

[
   {"fruit": "Apple", "vegetable":"Celery", "first_name":"Sam"}, 
   {"fruit": "Banana", "vegetable":"Onion", "first_name":"Beth"},
   {"fruit": "Pear", "vegetable":"Potato", "first_name":"John"},
   {"fruit": "Grape", "vegetable":"Broccoli", "first_name":"Daisy"},
   {"fruit": "Pineapple", "vegetable":"Sprouts", "first_name":"Jane"}
]

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    IIUC 您可以通过 (1) .explode() 和 (2) .to_dict() 来实现

    df.apply(pd.Series.explode).to_dict(orient='records')
    #output:
    [{'fruit': 'Apple', 'vegetable': 'Celery', 'first_name': 'Sam'},
     {'fruit': 'Banana', 'vegetable': 'Onion', 'first_name': 'Beth'},
     {'fruit': 'Pear', 'vegetable': 'Potato', 'first_name': 'John'},
     {'fruit': 'Grape', 'vegetable': 'Broccoli', 'first_name': 'Daisy'},
     {'fruit': 'Pineapple', 'vegetable': 'Sprouts', 'first_name': 'Jane'}]
    

    【讨论】:

    • 谢谢我结合你的建议来获得我的新专栏:pd.DataFrame({'party_items':df.apply(pd.Series.explode).to_dict(orient='records' )})
    【解决方案2】:

    您还可以使用to_dict 创建exploded DataFrame,然后调用pd.DataFrame。对于较小的列表,它会更快一些,但是一旦您拥有 10,000 多个项目,它基本上是相同的。

    pd.DataFrame(df.iloc[0].to_dict()).to_dict('records')
    
    [{'fruit': 'Apple', 'vegetable': 'Celery', 'first_name': 'Sam'},
     {'fruit': 'Banana', 'vegetable': 'Onion', 'first_name': 'Beth'},
     {'fruit': 'Pear', 'vegetable': 'Potato', 'first_name': 'John'},
     {'fruit': 'Grape', 'vegetable': 'Broccoli', 'first_name': 'Daisy'},
     {'fruit': 'Pineapple', 'vegetable': 'Sprouts', 'first_name': 'Jane'}]
    

    【讨论】:

      【解决方案3】:

      要处理的主要问题是扁平化字典中每个值的值。一个相当手动的实现是:

      for i in ["fruit","vegetable","first_name"]:    
              flat_list = [item for sublist in df[i] for item in sublist]    
              list.append(flat_list)
              
              list_of_dic = [] for i in range(5):    
                  dic = {}    
                  dic["furit"] = list[0][i]    
                  dic["vegetable"] = list[1][i]
                  dic["first_name"] = list[2][i]
                  list_of_dic.append(dic) 
          
             
              
      

      【讨论】:

        猜你喜欢
        • 2019-11-27
        • 2020-03-19
        • 2016-08-29
        • 2011-10-17
        • 2017-10-01
        • 1970-01-01
        • 2018-02-08
        • 2019-11-18
        • 1970-01-01
        相关资源
        最近更新 更多