【问题标题】:how to split a nested dictionary inside a column of a dataframe into new rows?如何将数据框列内的嵌套字典拆分为新行?
【发布时间】:2020-04-09 09:28:13
【问题描述】:

我有一个数据框:

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)

【问题讨论】:

  • col3的dtype是字符串还是对象?也就是说,它是否包含类似 JSON 的字符串,还是实际的 dict?
  • dtype 是对象
  • @Anti_cse51 和 df['Col3'].map(type).value_counts() 显示什么?
  • 49 1 @JonClements

标签: python pandas dataframe dictionary


【解决方案1】:

使用Series.str.get,但必要时先转换为字典:

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

【讨论】:

  • ast.literal_eval 拯救了这一天
【解决方案2】:

如果你喜欢长代码:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 2021-08-13
    相关资源
    最近更新 更多