我有一個 2D NumPy 陣列,專門用 1 和 0 填充。
a = [[0 0 0 0 1 0 0 0 1]
[1 1 1 1 1 1 1 1 1]
[1 1 1 1 1 1 1 1 1]
[1 1 1 1 0 0 0 0 1]
[1 1 1 1 1 1 1 1 1]
[1 1 1 0 1 1 1 1 1]
[1 1 1 1 1 1 0 0 1]
[1 1 1 1 1 1 1 1 1]]
為了獲取 0 的位置,我使用了以下代碼:
new_array = np.transpose(np.nonzero(a==0))
正如預期的那樣,我得到以下結果,顯示了陣列中 0 的位置
new_array = [[0 0]
[0 1]
[0 2]
[0 3]
[0 5]
[0 6]
[0 7]
[3 4]
[3 5]
[3 6]
[3 7]
[5 3]
[6 6]
[6 7]]
現在我的問題來了:如果所說的組大于 2,有沒有辦法在水平組的開始和結束處獲取 0 的位置?
編輯:如果組要在一行的末尾完成并繼續在它下面的一個,它將計為 2 個單獨的組。
我的第一個想法是實作一個程序,如果它們位于 0 之間,將洗掉 0,但我無法弄清楚如何做到這一點。
我希望“new_array”輸出為:
new_array = [[0 0]
[0 3]
[0 5]
[0 7]
[3 4]
[3 7]
[5 3]
[6 6]
[6 7]]
先謝謝了!!
編輯2:
感謝大家提供非常有用的見解,我能夠解決我遇到的問題。
為了滿足好奇心,這個資料代表了音樂資訊。我正在開發的程式的目的是根據影像(僅由水平線組成)創建樂譜。
一旦影像轉換為 1 和 0,我需要從中提取以下資訊:起始、音高和持續時間。這轉化為“x”軸上的位置、“y”軸上的位置和組的總長度。
由于 X 和 Y 位置相當容易獲得,因此我決定將它們與“持續時間”計算分開處理(這是本文要解決的主要問題)。
感謝您的幫助,我能夠解決 Duration 問題并創建一個包含所有必要資訊的新陣列:
[[0 0 4]
[5 0 3]
[4 3 4]
[6 6 2]]
Note that 1st column represent Onset, 2nd column represents Pitch, and 3rd column represents Duration.
It has also come to my attention the comment that suggested to add an identifier to each event. Eventually I will need to implement that to differentiate between different instruments (and later sending them to individual Midi channels). However, for this first iteration of the program that only aims to create a music score for a single instrument, it is not necessary since all events belong to a single instrument.
I have very little experience with programming, I don't know if this was the most efficient way of achieving my goal. Any suggestions are welcomed.
Thanks!
uj5u.com熱心網友回復:
一種更容易遵循的可能解決方案是:
b = np.diff(a, prepend=1) # prepend a column of 1s and detect
# jumps between adjacent columns (left to right)
y, x = np.where(b > 0) # find positions of the jumps 0->1 (left to right)
# shift positive jumps to the left by 1 position while filling gaps with 0:
b[y, x - 1] = 1
b[y, x] = 0
new_array = list(zip(*np.where(b)))
另一個是:
new_array = list(zip(*np.where(np.diff(a, n=2, prepend=1, append=1) > 0)))
兩種解決方案都基于np.diff計算連續列之間的差異(當axis=-1用于 2D 陣列時)。
uj5u.com熱心網友回復:
另一種解決方案的一個缺陷是它報告了所有的零序列,無論它們的長度如何。您的預期輸出也包含這樣的組,由 1 個或 2 個零組成,但我認為它不應該。
我的解決方案沒有上述缺陷。
處理相鄰相等元素 組的優雅工具是itertools.groupby,所以從:
import itertools
然后將您的預期結果生成為:
res = []
for rowIdx, row in enumerate(a):
colIdx = 0 # Start column index
for k, grp in itertools.groupby(row):
vals = list(grp) # Values in the group
lgth = len(vals) # Length of the group
colIdx2 = colIdx lgth - 1 # End column index
if k == 0 and lgth > 2: # Record this group
res.append([rowIdx, colIdx])
res.append([rowIdx, colIdx2])
colIdx = colIdx2 1 # Advance column index
result = np.array(res)
對于您的源資料,結果是:
array([[0, 0],
[0, 3],
[0, 5],
[0, 7],
[3, 4],
[3, 7]])
如您所見,它不包括第 5 行和第 6 行中較短的零序列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/416478.html
標籤:
上一篇:熊貓值查找但具有重復值
