2017-10-21 67 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验证这些值是否合理。