如何将数据帧列中的嵌套字典拆分为新行?

2024-04-26 07:08:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧:

Col1 Col2 Col3
01   ABC  {'link':'http://smthing1}
02   DEF  {'link':'http://smthing2}

我需要将col3拆分为新行: 预期输出数据帧:

Col1 Col2 Col3
01   ABC  'http://smthing1'
02   DEF  'http://smthing2'

这似乎不起作用:

df= df.apply(pd.Series)

Tags: 数据httpdfdeflinkcol2col3col1
2条回答

使用^{},但如有必要,首先转换为字典:

#converting to dicts
#import ast
#df['Col3'] = df['Col3'].apply(ast.literal_eval)
df['Col3'] = df['Col3'].str.get('link')

如果您喜欢长代码:

import pandas as pd

my_list = [[1,   'ABC',  {'link':'http://smthing1'}],  # list 
[2,   'DEF',  {'link':'http://smthing2'}]]

df = pd.DataFrame(my_list, columns=['col1', 'col2', 'col3']) #convert to pandas dataframe

convert_col3_to_dict = dict(df['col3']) #convert string to dict 

list1 = []
list2 = []

for i in range(len(my_list)):
    elements = my_list[i][:2]
    #remove empty list
    elements = [x for x in elements if x != []]
    # print(elements)
    list1.append(elements)

for key, val in convert_col3_to_dict.items(): #Iterating through the col3
for k,v in val.items(): #iterating through values in col3
    # print([v]) # printing the value
    list2.append([v])

new_list = []

for f, b in zip(list1, list2):
    # print(f, b)
    tem_list = f + b
    new_list.append(tem_list)

new_df = pd.DataFrame(new_list, columns=['col1', 'clo2', 'col3'])

print(new_df)

结果:

   col1 clo2             col3
0     1  ABC  http://smthing1
1     2  DEF  http://smthing2

相关问题 更多 >