簡體   English   中英

Python從多維numpy數組中的一個維度訪問所有條目

[英]Python access all entrys from one dimension in a multidimensional numpy array

我想操縱一個復雜的3d numpy數組的所有條目的數據。 我想要XY位置中所有子數組的所有條目。 我知道Matlab可以做類似的事情(使用變量指標:用於所有操作),我在下面用DARK [:] [1] [1]指出了這一點。 基本上,這意味着我要從所有子數組中的第二列開始輸入第二個條目。 有沒有辦法在python中做到這一點?

import numpy

# Creating a dummy variable of the type I deal with (If this looks crappy sorry, the variable actually comes from the output of d = pyfits.getdata()):
a = []
for i in range(3):
    d = numpy.array([[i, 2*i], [3*i, 4*i]])
    a.append(d)

print a
# Pseudo code:
print 'Second row, second column: ', a[:][1][1]

我期望這樣的結果:

[array([[ 0,  0],[ 0,  0]]),
array([[ 1,  2],[ 3,  4]]),
array([[ 2,  4],[ 6,  8]])]

Second row, second column: [0, 4, 8]

您可以使用略有不同的語法來做到這一點。

import numpy as np

a = np.arange(27).reshape(3,3,3) # Create a 3x3x3 3d array

print("3d Array:")
print(a)
print("Second Row, Second Column: ", a[:,1,1])

輸出:

>>> 3d Array:
 [[[ 0  1  2]
   [ 3  4  5]
   [ 6  7  8]]

  [[ 9 10 11]
   [12 13 14]
   [15 16 17]]

  [[18 19 20]
   [21 22 23]
   [24 25 26]]]

>>> Second Row, Second Column:  [ 4 13 22]

找到了解決方案,謝謝DivakareeScott

import numpy as np

# Creating a dummy variable of the type I deal with (If this looks crappy sorry, the variable actually comes from the output of d = pyfits.getdata()):
a = []
for i in range(3):
    d = np.array([[i, 2*i], [3*i, 4*i]])
    a.append(d)

# print variable
print np.array(a)
print 'Second row, second column: ', np.array(a)[:, 1, 1]

# Alternative solution:
a = np.asarray(a)
print a
print 'Second row, second column: ', a[:,1,1]

結果:

[[[0 0][0 0]]
 [[1 2][3 4]]
 [[2 4][6 8]]]
Second row, second column:  [0 4 8]

暫無
暫無

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

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