Python Array Slice With Comma?

点点圈 提交于 2020-01-09 02:13:09

问题


I was wondering what the use of the comma was when slicing Python arrays - I have an example that appears to work, but the line that looks weird to me is

p = 20*numpy.log10(numpy.abs(numpy.fft.rfft(data[:2048, 0])))

Now, I know that when slicing an array, the first number is start, the next is end, and the last is step, but what does the comma after the end number designate? Thanks.


回答1:


It is being used to extract a specific column from a 2D array. Refer to the first examples here.

So your example would extract column 0 (the first column) from the first 2048 rows (0 to 2047). Note however that this syntax will only work for numpy arrays and not general python lists.




回答2:


Empirically - create an array using numpy

m = np.fromfunction(lambda i, j: (i +1)* 10 + j + 1, (9, 4), dtype=int)

which assigns an array like below to m

array(
      [[11, 12, 13, 14],
       [21, 22, 23, 24],
       [31, 32, 33, 34],
       [41, 42, 43, 44],
       [51, 52, 53, 54],
       [61, 62, 63, 64],
       [71, 72, 73, 74],
       [81, 82, 83, 84],
       [91, 92, 93, 94]])

Now for the slice

m[:,0]

giving us

array([11, 21, 31, 41, 51, 61, 71, 81, 91])

I may have misinterpreted Khan Academy (so take with grain of salt):

In linear algebra terms, m[:,n] is taking the nth column vector of the matrix m

See Abhranil's note how this specific interpretation only applies to numpy




回答3:


It slices with a tuple. What exactly the tuple means depends on the object being sliced. In NumPy arrays, it performs a m-dimensional slice on a n-dimensional array.

>>> class C(object):
...   def __getitem__(self, val):
...     print val
... 
>>> c = C()
>>> c[1:2,3:4]
(slice(1, 2, None), slice(3, 4, None))
>>> c[5:6,7]
(slice(5, 6, None), 7)


来源:https://stackoverflow.com/questions/9972391/python-array-slice-with-comma

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!