Py学习  »  Python

列表到pandas数据帧的python字典

Simon • 5 年前 • 1653 次点击  

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

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
 
1653 次点击  
文章 [ 1 ]  |  最新文章 5 年前
jpp
Reply   •   1 楼
jpp    6 年前

您可以使用字典理解将输入重组为字典字典。然后使用 from_dict 具有 orient='index' :

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

d = {k: dict(map(str.strip, x.split(':')) for x in v) for k, v in user_dict.items()}

df = pd.DataFrame.from_dict(d, orient='index')

df['att_1'] = pd.to_numeric(df['att_1'])

print(df)

           att_1     att_2
Category 1     1  whatever
Category 2    23   another

如上所述,您需要根据需要将序列转换为数字。