pandas:从字典创建数据框

时间:2017-02-14 17:38:24

标签: python pandas

拿字典:

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

如何使用此词典并将其转换为值为列的数据框?即我想要一个数据框显示:

   ham   chicken  beef
0   a       c       d
1   b       e       

似乎根本无法获得这种形式!

由于

这是一个不同的问题,另一个只是询问如何将字典的值放入数据框中,我问如何获得我概述的特定形式

2 个答案:

答案 0 :(得分: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'

答案 1 :(得分:2)

我看到Jan刚刚发布了一个很好的答案,但我想表明你也可以使用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
相关问题