2016-06-11 717 views
3

我有一個csv文件,我使用Pandas轉換爲數據框。這裏的數據幀:將數據框轉換爲Python中的字典

Customer ProductID Count 

John  1   50 
John  2   45 
Mary  1   75 
Mary  2   10 
Mary  5   15 

我需要一本字典的形式,看起來像這樣的輸出:

{ProductID:1, Count:{John:50, Mary:75}}, 
{ProductID:2, Count:{John:45, Mary:10}}, 
{ProductID:5, Count:{John:0, Mary:15}} 

我讀了如下回答:

python pandas dataframe to dictionary

Convert dataframe to dictionary

這是我遇到的代碼:

df = pd.read_csv('customer.csv') 
dict1 = df.set_index('Customer').T.to_dict('dict') 
dict2 = df.to_dict(orient='records') 

,這是我的電流輸出:

dict1 = {'John': {'Count': 45, 'ProductID': 2}, 'Mary': {'Count': 15, 'ProductID': 5}} 

dict2 = [{'Count': 50, 'Customer': 'John', 'ProductID': 1}, 
{'Count': 45, 'Customer': 'John', 'ProductID': 2}, 
{'Count': 75, 'Customer': 'Mary', 'ProductID': 1}, 
{'Count': 10, 'Customer': 'Mary', 'ProductID': 2}, 
{'Count': 15, 'Customer': 'Mary', 'ProductID': 5}] 

回答

4

IIUC你可以使用:

d = df.groupby('ProductID').apply(lambda x: dict(zip(x.Customer, x.Count))) 
     .reset_index(name='Count') 
     .to_dict(orient='records') 

print (d) 
[{'ProductID': 1, 'Count': {'John': 50, 'Mary': 75}}, 
{'ProductID': 2, 'Count': {'John': 45, 'Mary': 10}}, 
{'ProductID': 5, 'Count': {'Mary': 15}}]