【问题标题】:populating nested dictionaries with rows from Pandas data frame用 Pandas 数据框中的行填充嵌套字典
【发布时间】:2019-12-09 09:14:32
【问题描述】:

我正在尝试通过迭代嵌套字典并使用 Pandas 数据框的一行中的条目填充每个子字典的值,从而在 Python 中使用来自 Pandas 数据框的条目来填充字典字典。

虽然子词典的数量与数据框中的行数一样多,但所有词典都使用数据框最后一行的数据填充,而不是为每个词典使用每一行。

这是一个玩具可重现的例子。

import pandas as pd

# initialize an empty df
data = pd.DataFrame()

# populate data frame with entries
data['name'] = ['Joe Smith', 'Mary James', 'Charles Williams']
data['school'] =  ["Jollywood Secondary", "Northgate Sixth From", "Brompton High"]
data['subjects'] = [['Maths', 'Art', 'Biology'], ['English', 'French', 'History'], ['Chemistry', 'Biology', 'English']]

# use dictionary comprehensions to set up main dictionary and sub-dictionary templates

# sub-dictionary
keys = ['name', 'school', 'subjects']
record = {key: None for key in keys}

# main dictionary
keys2 = ['cand1', 'cand2', 'cand3']
candidates = {key: record for key in keys2}

# as a result i get something like this
# {'cand1': {'name': None, 'school': None, 'subjects': None},
# 'cand2': {'name': None, 'school': None, 'subjects': None},
# 'cand3': {'name': None, 'school': None, 'subjects': None}}

# iterate through main dictionary and populate each sub-dict with row of df
for i, d in enumerate(candidates.items()):

    d[1]['name'] = data['name'].iloc[i]
    d[1]['school'] = data['school'].iloc[i]
    d[1]['subjcts'] = data['subjects'].iloc[i]

# what i end up with is the last row entry in each sub-dictionary
#{'cand1': {'name': 'Charles Williams',
#  'school': 'Brompton High',
#  'subjects': None,
#  'subjcts': ['Chemistry', 'Biology', 'English']},
# 'cand2': {'name': 'Charles Williams',
#  'school': 'Brompton High',
#  'subjects': None,
#  'subjcts': ['Chemistry', 'Biology', 'English']},
# 'cand3': {'name': 'Charles Williams',
#  'school': 'Brompton High',
#  'subjects': None,
#  'subjcts': ['Chemistry', 'Biology', 'English']}}

我需要如何修改我的代码以使每个字典填充我的数据框中的不同行?

【问题讨论】:

    标签: pandas loops dataframe dictionary indexing


    【解决方案1】:

    我没有通过您的代码来查找错误,因为解决方案是使用方法to_dict 的单行代码。

    这是一个包含示例数据的最小工作示例。

    import pandas as pd
    
    # initialize an empty df
    data = pd.DataFrame()
    
    # populate data frame with entries
    data['name'] = ['Joe Smith', 'Mary James', 'Charles Williams']
    data['school'] =  ["Jollywood Secondary", "Northgate Sixth From", "Brompton High"]
    data['subjects'] = [['Maths', 'Art', 'Biology'], ['English', 'French', 'History'], ['Chemistry', 'Biology', 'English']]
    
    # redefine index to match your keys
    data.index = ['cand{}'.format(i) for i in range(1,len(data)+1)]
    
    # convert to dict
    data_dict = data.to_dict(orient='index')
    
    print(data_dict)
    

    这看起来像这样

    {'cand1': {
         'name': 'Joe Smith', 
         'school': 'Jollywood Secondary', 
         'subjects': ['Maths', 'Art', 'Biology']},
     'cand2': {
         'name': 'Mary James', 
         'school': 'Northgate Sixth From', 
         'subjects': ['English', 'French', 'History']},
     'cand3': {
         'name': 'Charles Williams', 
         'school': 'Brompton High', 
         'subjects': ['Chemistry', 'Biology', 'English']}}
    

    【讨论】:

      【解决方案2】:

      考虑避免绕道而行,因为 Pandas 维护了各种方法来渲染嵌套结构,例如 to_dictto_json。具体来说,考虑添加一个新列 cand 并将其设置为to_dict 输出的索引:

      data['cand'] = 'cand' + pd.Series((data.index.astype('int') + 1).astype('str'))
      
      mydict = data.set_index('cand').to_dict(orient='index')
      
      print(mydict)
      
      {'cand1': {'name': 'Joe Smith', 'school': 'Jollywood Secondary', 
                 'subjects': ['Maths', 'Art', 'Biology']}, 
       'cand2': {'name': 'Mary James', 'school': 'Northgate Sixth From', 
                 'subjects': ['English', 'French', 'History']}, 
       'cand3': {'name': 'Charles Williams', 'school': 'Brompton High', 
                 'subjects': ['Chemistry', 'Biology', 'English']}}
      

      【讨论】:

        猜你喜欢
        • 2018-01-20
        • 2018-09-27
        • 2022-01-02
        • 2016-02-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-13
        • 2021-11-28
        相关资源
        最近更新 更多