我有兩個 NumPy 陣列:
一個命名標簽和另一個組件:
labels = array([ 0, 0, 0, 3, 0, 0, 0, 1, 0, 1, 0, 0, 2, 2, 3, 4, -1])
component = array([ 1.05325312, 1.0206622 , 1.0372349 , 1.06951778, 0.96379751, 0.98862576, 1.01135931, 0.92633951, 1.09095756, 1.1662432, 1.17794883, 1.23006966, 1.25465147, 1.27054648, 1.18940802, 0.91512676, 0.81926385])
我希望標簽陣列成為字典的鍵,并將組件中的元素排序到鍵中。
兩個陣列的形狀相同,標簽中元素的位置對應于組件中的位置。
我試圖得到這樣的東西:
{'-1': [0.81926385],
'0': [1.05325312, 1.0206622, 1.0372349, 0.96379751, 0.98862576, 1.01135931, 1.09095756],
'1': [0.92633951, 1.1662432],
'2': [1.25465147, 1.27054648],
'3': [1.06951778, 1.18940802],
'4': [0.91512676]}
我已經嘗試使用 zip 和幾種不同的方法,但我不知道如何將值拆分為它們的關聯鍵。誰能指出我正確的方向?
d = dict(zip(labels, components))
uj5u.com熱心網友回復:
不能直接用dict(zip(**)),別忘了字典里的key是唯一的,加個判斷可能會解決問題,我提供的方式是通過回圈結合an if 陳述句,如果鍵存在則追加,如果不存在則創建一個空串列:
from numpy import array
labels = array([ 0, 0, 0, 3, 0, 0, 0, 1, 0, 1, 0, 0, 2, 2, 3, 4, -1])
component = array([ 1.05325312, 1.0206622 , 1.0372349 , 1.06951778, 0.96379751, 0.98862576, 1.01135931, 0.92633951, 1.09095756, 1.1662432, 1.17794883, 1.23006966, 1.25465147, 1.27054648, 1.18940802, 0.91512676, 0.81926385])
dic = {}
for key, value in zip(labels, component):
if key not in dic:
dic[key] = [value]
else:
dic[key].append(value)
print(dic)
如果你想更簡潔,你可以考慮使用 defaultdict 以及 OrderedDict
uj5u.com熱心網友回復:
這是一個完美的用例collections.defaultdict:
from collections import defaultdict
d = defaultdict(list)
for l,c in zip(labels, component):
d[l].append(c)
d = dict(d)
輸出:
{0: [1.05325312, 1.0206622, 1.0372349, 0.96379751, 0.98862576, 1.01135931, 1.09095756, 1.17794883, 1.23006966],
3: [1.06951778, 1.18940802],
1: [0.92633951, 1.1662432],
2: [1.25465147, 1.27054648],
4: [0.91512676],
-1: [0.81926385]}
uj5u.com熱心網友回復:
我想到的另一種選擇是使用熊貓。
將兩個陣列放入各自的列中,并按標簽對它們進行分組。
我希望保持 numpy 的速度,但如果需要的話。
pd.DataFrame(data=[X.flatten(), labels], index={'Levels', 'Zone'}).T
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/436256.html
