2017-10-21 53 views
0

我試圖從一個文件構建一個翻譯後的矩陣。該文件看起來像下面,代表開始和偏移時間爲鋼琴音符構建一個numpy maxtix

OnsetTime OffsetTime MidiPitch 
0.500004 0.85356  37 
1.20712  1.50441  38 
1.80171  2.0517  39 
... 

我試圖拉平這鋼琴狀態表示與事件時間像這樣

Event State 
time  Piano state, array of length 88 
... 

要做到這一點,我已經構建瞭如下代碼

eventArray = np.array([]) 
with open('event_log.txt') as tsv: 
     noteState = [0] * 88 
     iterator = iter(csv.reader(tsv, dialect="excel-tab")) 
     next(iterator) 
     for line in iterator: 
      notePosition = int(float(line[2])) - 21 
      noteState[notePosition] = 1 
      np.concatenate(eventArray, np.array([float(line[0]), noteState])) 
      noteState[notePosition] = 0 
      np.concatenate(eventArray, np.array([float(line[1]), noteState])) 

但是,當我執行此我得到以下錯誤

File "main.py", line 32, in <module> 
    np.concatenate(eventArray, np.array([float(line[0]), noteState])) 
    ValueError: setting an array element with a sequence. 

我應該如何構建這個矩陣?我正在使用numpy來根據需要對矩陣進行切片和重塑。

編輯

在註釋中嘗試建議後,我現在有

np.concatenate(eventArray, np.array([[float(line[0])], noteState])) 

而且收到以下錯誤

Traceback (most recent call last): 
    File "main.py", line 32, in <module> 
    np.concatenate(eventArray, np.array([[float(line[0])], noteState])) 
TypeError: only integer scalar arrays can be converted to a scalar index 
+0

這是微妙的,但它導致了一個新的錯誤'TypeError:只有整數標量數組可以轉換爲標量索引' – JME

+0

我認爲我錯了那一個我道歉 – GWW

回答

2

不要concatenate反覆。 np.concatenate每一步都會返回一個新的數組。它不會修改數組。

alist = [] 
with open('event_log.txt') as tsv: 
     noteState = [0] * 88 
     iterator = iter(csv.reader(tsv, dialect="excel-tab")) 
     next(iterator) 
     for line in iterator: 
      notePosition = int(float(line[2])) - 21 
      noteState[notePosition] = 1 
      alist.append(np.array([float(line[0]), noteState])) 
      noteState[notePosition] = 0 
      alist.append(np.array([float(line[1]), noteState])) 

這應該創建一個數組列表。如果這些陣列的長度都是相同的,那麼

arr = np.array(alist) 

應該創建一個2d浮點數組。如果他們的長度不同,我會建議

arr = np.concatenate(alist) 

使平面(1d)陣列具有相同的值。

我假設代碼的其餘部分是正確的。

打印alist驗證這些值是否合理。