【问题标题】:Iterate over a list of dictionaries in pandas column and create new columns遍历 pandas 列中的字典列表并创建新列
【发布时间】:2021-02-21 09:50:15
【问题描述】:

我想从 pandas 数据框列解析 json 字典,遍历这些字典并将它们分配给新的列值。

这是一列数据框:df['Column'][0]

[{'Name': 'Vacant', 'Value': 3904000, 'Unit': 'Qty'},
 {'Name': 'Vacant', 'Value': 11.7, 'Unit': 'Pct'},
 {'Name': 'Absorption', 'Value': 415000, 'Unit': 'Units'},
 {'Name': 'AbsorpOcc', 'Value': 1.4, 'Unit': 'Pct'},
 {'Name': 'Occupied', 'Value': None, 'Unit': 'Qty'}]

我有以下代码来遍历 pandas 数据框中的每一行,然后遍历列表中的每个字典并创建新列。

# Iterate over dataframe to parse select rows   
# Declare array
s = ""

#Iterate over each row in Dataframe
for index, row in df.iterrows():
    
    # Iterate over each json object in each row in DataFrame
    for i in range(0,len(row['Column'])):
        
        for k,v in row['Column'][i].items():
            
            # Concat string labels to assign them as column names
            if type(v) == str:
            
                s += v
            
        print(s)
                  

预期输出,新列:

【问题讨论】:

    标签: python pandas dataframe dictionary


    【解决方案1】:

    您对处理数据框的“列”列有特定要求。 我认为你应该使用 apply https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html。此外,此更改将在数据框中进行,因此您的函数可能是。

    def func(row):
        # your parsing logic
        index = row.name
        # {'Name': 'Vacant', 'Value': 3904000, 'Unit': 'Qty'}
        # col = 'Vacant', value = 3904000
        df.loc[index, col] = value
    df.apply(func, axis=1)
    

    【讨论】:

    • 是的,我正在寻找那个解析逻辑。 .apply 有道理。
    猜你喜欢
    • 2020-11-08
    • 2021-04-14
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-29
    相关资源
    最近更新 更多