2017-02-14 103 views
2

拿字典:大熊猫:从字典中创建一个数据帧

dict = {'a':'ham', 'b': 'ham', 'c': 'chicken', 'd': 'beef', 'e': 'chicken'} 

我怎么拿这本字典,把它变成一个数据帧,其中值是列?即我想要一个数据帧显示:

ham chicken beef 
0 a  c  d 
1 b  e  

似乎无法得到它的这种形式!

感谢

这是一个不同的问题,另一种是简单地询问如何买到字典的值转换为数据帧,我询问如何获取特定形式我概述

+4

这是一个不同的问题我不知道为什么这被标记为重复 – user33484

+1

命令是否重要?您可能需要将其转换为记录形式的某种有序数据。 –

回答

2

的一点点转换“魔术”:

import pandas as pd 

d = {'a':'ham', 'b': 'ham', 'c': 'chicken', 'd': 'beef', 'e': 'chicken'} 

new_dict = dict() 
for key in d: 
    col = d[key] 
    try: 
     new_dict[col].append(key) 
    except: 
     new_dict[col] = [key] 

df = pd.DataFrame.from_dict(new_dict, orient='index').transpose() 
print(df) 

# chicken ham beef 
# 0  c a  d 
# 1  e b None 

首先,走过你原来的字典和一个叫做new_dict新字典创建列表。从这一个电话from_dict()orient='index'

2

我看到扬刚刚发布了一个很好的答案,但我想表明,你也可以使用defaultdict和列表解析来做到这一点。

import pandas as pd 
from collections import defaultdict 

dict1 = {'a':'ham', 'b': 'ham', 'c': 'chicken', 'd': 'beef', 'e': 'chicken'} 

# Set the default as an empty list to store multiple strings with an order 
reversed_dict = defaultdict(list) 

# Reverse the key-value pairs 
for k, v in dict1.items(): 
    reversed_dict[v].append(k) 

# Convert each list to a Series and make the dataframe 
pd.DataFrame(dict([(k, pd.Series(v)) for k, v in reversed_dict.items()])) 

# beef chicken ham 
# 0 d  c a 
# 1 NaN  e b