資料框中有兩列,我想將第一列值用作另一列的鍵作為字典
假設df如下
| 多變的 | 價值 | 價值分配 | |
|---|---|---|---|
| 1 | 第一種顏色 | ['黑色'、'藍色'、'綠色'、'紅色'、'紫色'] | [0.3, 0.25, 0.2, 0.15, 0.1] |
| 5 | 第二種顏色 | ['深藍色'、'青色'、'綠色'、'紫色'、'紅色... | [0.5, 0.25, 0.15, 0.25, 0.25, 0.15, 0.1] |
| 6 | 第三色 | ['紅色'、'橙色'、'黃色'、'綠色'、'藍色'、'... | [1.0, 0.0, 0.0, 0.0, 0.0, 0.0] |
所以假設我想創建一個像
{'第一種顏色':{'黑色':0.3,'藍色':0.25,'綠色':0.2,'紅色':0.15,'紫色':0.1}
所以我嘗試了以下
dict(zip(df['Value'],df['Value Distribution']))
將第二個和第三個列值壓縮到字典中,而不是它創建了這個字典
"['Black', 'Blue', 'Green', 'Red', 'Purple']":"[0.3, 0.25, 0.2, 0.15, 0.1]"
將串列作為字串讀取
uj5u.com熱心網友回復:
嘗試使用explode和groupby:
df = df.explode(["Value", "Value Distribution"])
>>> df.groupby("Variable").apply(lambda x: dict(zip(x["Value"],x["Value Distribution"]))).to_dict()
{'First Color': {'Black': 0.3,
'Blue': 0.25,
'Green': 0.2,
'Red': 0.15,
'Purple': 0.1},
'Second Color': {'Deep Blue': 0.5,
'Teal': 0.25,
'Green': 0.15,
'Purple ': 0.25,
'Red': 0.25},
'Third Color': {'Red': 1.0,
'Orange': 0.0,
'Yellow': 0.0,
'Green': 0.0,
'Blue': 0.0}}
uj5u.com熱心網友回復:
這可能是最容易布置的iterrows:
df = pd.DataFrame(
data = [
['First colour', ['Black', 'Blue', 'Green', 'Red', 'Purple'], [0.3, 0.25, 0.2, 0.15, 0.1]],
['Second Color', ['Red', 'Orange', 'Yellow', 'Green', 'Blue'], [0.5, 0.25, 0.15, 0.25, 0.25, 0.15, 0.1]]
],
columns=['Variable', 'Value', 'Value Distribution']
)
dict_result = {}
for index, row in df.iterrows():
dict_result[row['Variable']] = dict(zip(row['Value'],row['Value Distribution']))
uj5u.com熱心網友回復:
dct = df.set_index('Variable').apply(lambda x: dict(zip(x["Value"], x["Value Distribution"])), axis=1).to_dict()
輸出:
>>> dct
{'First Color': {'Black': 0.3,
'Blue': 0.25,
'Green': 0.2,
'Red': 0.15,
'Purple': 0.1}}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/388305.html
上一篇:堅持撰寫python串列縮減程式
