Py学习  »  Python

列表到pandas数据帧的python字典

Simon • 5 年前 • 1655 次点击  

我正在尝试将一个列表字典(看起来像一个字典,但很不幸是一个列表字典)转换为一个数据帧。我想从列表对象中获取列名。到目前为止,我找到了一种将字典转换为数据帧的方法,但是列没有适当的名称,并且值仍然包含列名。

user_dict = {'Category 1': ['att_1: 1', 'att_2:  whatever'],
                  'Category 2': ['att_1 : 23', 'att_2 : another']}

res = pd.DataFrame.from_dict(user_dict, orient='index')
res.columns = [f'SYN{i+1}' for i in res]

示例输出:

                att_1 | att_2 

Category_1       1 | whatever

Category_1       23 | another

我在考虑使用unlist或regex,但我不确定在哪里输入。非常感谢您的帮助!谢谢你

编辑: 我最后的尝试在这里结束:

pd.DataFrame.from_dict({(i,j): to_dict(unlist(user_dict[i][j])) 
                       for i in user_dict.keys() 
                       for j in user_dict[i].keys()},
                   orient='index')
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/39893
 
1655 次点击  
文章 [ 1 ]  |  最新文章 5 年前