2014-10-31 45 views
1

雖然我找到關於如何將pandas DataFrame轉換爲字典的幫助和文檔,以便列是鍵和值是行,但我發現自己卡住了,希望獲得列值之一作爲鍵和另一列值的相關值,所以像這樣長格式熊貓數據框到字典

a b 
1 car 
1 train 
2 boot 
2 computer 
2 lipstick 

一個DF轉換爲以下詞典{'1': ['car','train'], '2': ['boot','computer','lipstick]}

我有一種感覺它的東西很簡單,但我的想法。我試過df.groupby('a').to_dict()但未成功

有什麼建議嗎?

回答

1

您不能在GROUPBY的結果進行to_dict(),但你可以使用它來執行你自己的字典構造。以下代碼將與您提供的示例一起使用。

import pandas as pd 

df = pd.DataFrame(dict(a=[1,1,2,2,2], 
         b=['car', 'train', 'boot', 'computer', 'lipstick'])) 
# Using a loop 
dt = {} 
for g, d in df.groupby('a'): 
    dt[g] = d['b'].values 

# Using dictionary comprehension 
dt2 = {g: d['b'].values for g, d in df.groupby('a')} 

現在無論dtdt2將字典是這樣的:

{1: array(['car', 'train'], dtype=object), 
2: array(['boot', 'computer', 'lipstick'], dtype=object)} 

當然你也可以把numpy的陣列回列表,如果你願意的話。

+0

完美的作品像一個魅力非常感謝!出於某種原因,您構建pd.DataFrame的行會返回「dict」不可調用的錯誤。以防萬一你想編輯它以供將來參考。 – Bastien 2014-10-31 23:29:16

+0

這很奇怪,對我來說工作正常,而且看起來不像是一個錯字......嗯。 – Ajean 2014-11-01 00:05:43

+0

哦,廢料,我只是再次測試它,它的工作。也許我第一次嘗試時做錯了什麼。無論如何,再次感謝! – Bastien 2014-11-01 00:09:49

1

是的,因爲DataFrameGroupBy沒有to_dict的屬性,只有DataFrameto_dict屬性。

DataFrame.to_dict(outtype ='dict') 將DataFrame轉換爲字典。

你可以閱讀更多關於DataFrame.to_dicthere

看看這個:

import pandas as pd 

df = pd.DataFrame([np.random.sample(9), np.random.sample(9)]) 
df.columns = [c for c in 'abcdefghi'] 
# it will convert the DataFrame to dict, with {column -> {index -> value}} 
df.to_dict() 
{'a': {0: 0.53252618404947039, 1: 0.78237275521385163}, 
'b': {0: 0.43681232450879315, 1: 0.31356312459390356}, 
'c': {0: 0.84648298651737541, 1: 0.81417040486070058}, 
'd': {0: 0.48419015448536995, 1: 0.37578177386187273}, 
'e': {0: 0.39840348154035421, 1: 0.35367537180764919}, 
'f': {0: 0.050381560155985827, 1: 0.57080653289506755}, 
'g': {0: 0.96491634442628171, 1: 0.32844653606404517}, 
'h': {0: 0.682, 1: 0.0097104037581828839}, 
'i': {0: 0.66836630467152902, 1: 0.69104505886376366}} 

type(df) 
pandas.core.frame.DataFrame 

# DataFrame.groupby is another type 
type(df.groupby('a')) 
pandas.core.groupby.DataFrameGroupBy 

df.groupby('a').to_dict() 
AttributeError: Cannot access callable attribute 'to_dict' of 'DataFrameGroupBy' objects, try using the 'apply' method 
+0

疑難雜症感謝指點! – Bastien 2014-10-31 23:30:38

2

您可以認爲這是一個GROUPBY聚集(即,果然每組爲一個值的操作 - 在此情況下一個列表):

In [85]: df.groupby(['a'])['b'].agg(lambda grp: list(grp)) 
Out[85]: 
a 
1     [car, train] 
2 [boot, computer, lipstick] 
dtype: object 

In [68]: df.groupby(['a'])['b'].agg(lambda grp: list(grp)).to_dict() 
Out[68]: {1: ['car', 'train'], 2: ['boot', 'computer', 'lipstick']} 
+0

哦,那也行! – Bastien 2014-11-01 01:07:04