我正在嘗試從熊貓資料框中獲取資料并將其轉換為所需的字典。以下是資料示例:
data =[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1],[0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 2]]
Utable = pd.DataFrame(data, columns =['Type1', 'Type2', 'Type3', 'Type4', 'Type5', 'Type6', 'Type7', 'Type8', 'ID'])
我需要的字典是作為 dict 鍵的 ID 記錄,并且值需要是從列名確定的不可接受的型別 #s 的串列。如果型別為 0.0,則型別是不可接受的。所以對于這個例子,輸出將是:
{1: [1, 2, 3, 4, 5, 6, 7, 8], 2: [1, 2, 4, 5, 6, 7, 8]}
我可以弄清楚如何使用以下方法獲取存盤為串列的型別值,其中 ID 作為 dict 鍵:
U = Utable.set_index('ID').T.to_dict('list')
這使:
{1: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], 2: [0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]}
但我不知道如何從存盤在串列中的列名中獲取內容作為 dict 值。
非常感謝您的幫助。
uj5u.com熱心網友回復:
orient=index您可以在轉換為字典時使用該引數;然后使用串列推導獲取所需的串列作為值:
out = {k: [int(i[-1]) for i, v in d.items() if v==0]
for k, d in Utable.set_index('ID').to_dict('index').items()}
輸出:
{1: [1, 2, 3, 4, 5, 6, 7, 8], 2: [1, 2, 4, 5, 6, 7, 8]}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/446234.html
