2017-07-25 49 views
0

我的數據框有'id_one',每個id可以有多個'id_twos'。每個id_two還具有存儲在其他列中的許多描述性特徵。 這是一個示例數據集。從(pandas)組中的多列創建詞典

d = {'id_one' : pd.Series([123, 123, 123]), 
    'id_two' : pd.Series([456, 567, 678]), 
    'descriptor' : pd.Series(['blue','yellow', 'green'])} 

df = pd.DataFrame(d) 

我需要讓我的數據幀在每個「id_one」一排的形式,其中「山坳」我店「id_one」和「列B」我店「id_two的所有值'作爲字典鍵和相應的描述符存儲爲字典值。

任何幫助將不勝感激,謝謝。

回答

1

這是你在找什麼?

df.groupby('id_one').apply(lambda x: dict(zip(x['id_two'], x['descriptor']))).reset_index().rename(columns={"id_one":"col a", 0:"col b"}) 
# col a           col b 
# 0 123 {456: u'blue', 678: u'green', 567: u'yellow'}