簡體   English   中英

Python-反轉以特定循環順序生成的數據

[英]Python - Reversing data generated with particular loop order

問題:如何更有效地執行以下任務?

我的問題如下。 我在實際物理空間(x,y,z)中有一個(大型)3D點數據集。 它是由嵌套的for循環生成的,如下所示:

# Generate given dat with its ordering
x_samples = 2
y_samples = 3
z_samples = 4
given_dat = np.zeros(((x_samples*y_samples*z_samples),3))
row_ind = 0
for z in range(z_samples):
    for y in range(y_samples):
        for x in range(x_samples):
            row = [x+.1,y+.2,z+.3]
            given_dat[row_ind,:] = row
            row_ind += 1
for row in given_dat:
    print(row)`

為了將其與另一組數據進行比較,我想將給定數據重新排序為所需的順序,如下所示(我知道這是非正統的):

# Generate data with desired ordering
x_samples = 2
y_samples = 3
z_samples = 4
desired_dat = np.zeros(((x_samples*y_samples*z_samples),3))
row_ind = 0
for z in range(z_samples):
    for x in range(x_samples):
        for y in range(y_samples):
            row = [x+.1,y+.2,z+.3]
            desired_dat[row_ind,:] = row
            row_ind += 1
for row in desired_dat:
    print(row)

我編寫了一個函數,該函數可以實現我想要的功能,但是它非常慢且效率低下:

def bad_method(x_samp,y_samp,z_samp,data):
    zs = np.unique(data[:,2])
    xs = np.unique(data[:,0])
    rowlist = []
    for z in zs:
        for x in xs:
            for row in data:
                if row[0] == x and row[2] == z:
                rowlist.append(row)
    new_data = np.vstack(rowlist)
    return new_data
# Shows that my function does with I want
fix = bad_method(x_samples,y_samples,z_samples,given_dat)    
print('Unreversed data')
print(given_dat)
print('Reversed Data')
print(fix)
# If it didn't work this will throw an exception
assert(np.array_equal(desired_dat,fix))

如何改善功能,使其更快? 我的數據集通常有大約200萬行。 一定可以通過一些聰明的切片/索引來做到這一點,我敢肯定它會更快,但是我很難弄清楚該怎么做。 謝謝你的幫助!

您可以調整數組的形狀,根據需要交換軸,然后重新調整形狀:

# (No need to copy if you don't want to keep the given_dat ordering)
data = np.copy(given_dat).reshape(( z_samples, y_samples, x_samples, 3))
# swap the "y" and "x" axes
data = np.swapaxes(data, 1,2)
# back to 2-D array
data = data.reshape((x_samples*y_samples*z_samples,3))

assert(np.array_equal(desired_dat,data))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM