简体   繁体   English

将列表字典分为列和值

[英]separate list dictonary into columns and values

I have data frame which contains a column "ExtData" with values [{"key":"title","value":"activation"},{"key":"remarks","value":"activation"}] 我有一个数据框,其中包含一列“ ExtData”,其值为[{"key":"title","value":"activation"},{"key":"remarks","value":"activation"}]

I have to separate this data and create a new data frame with "title" and "remarks" column name and their value "activation" ie "key" is column name and their "value" as value. 我必须分离这些数据,并使用“标题”和“备注”列名及其值“激活”创建一个新的数据框,即“键”是列名并将其“值”作为值。

I have data frame like this 我有这样的数据框

partner               ExtData
xyz          [{"key":"title","value":"activation"}, {"key":"remarks","value":"activation"}]
abc          [{"key":"title","value":"activation"}, {"key":"remarks","value":"activation"}]

I need output as new data frame with 我需要输出为新的数据框

**partner**   **title**      **remarks**
xyz           activation     activation
abc           activation     activation

using pandas and python. 使用pandas和python。


Here is solution, using DataFrame.apply method: 这是使用DataFrame.apply方法的解决方案:

def separate_extdata(row):
    for d in row['ExtData']:
            row[d['key']] = d['value']
    return row.drop('ExtData')

df = pd.DataFrame(
    [
      ('xyz', [{"key": "title", "value": "activation"},
               {"key":"remarks","value":"activation"}]), 
      ('abc', [{"key":"title","value":"activation"}, 
               {"key":"remarks","value":"activation"}])], 
    columns=['partner', 'ExtData']
)
df.apply(separate_extdata, axis=1)
#   partner       title     remarks
# 0     xyz  activation  activation
# 1     abc  activation  activation
new_df = pandas.Dataframe()
new_index = 0
for i, row in df.iterrows():
    if 'key' in row['ExtData']:
       k = row['ExtData']['key']
       v = row['ExtData']['value']
       new_df.loc[new_index, k] = v
       new_index+=1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM