-2

I want to copy every 2nd matrix element in Python.

For example:

arr1 = [[1, 2, 3, 4, 5], 
        [6, 7, 8, 9, 10], 
        [11, 12, 13, 14, 15]]

The desired array should be:

       [2, 4]
       [7, 9]
       [12, 14]

What's the easiest way to accomplish that?

cs95
  • 379,657
  • 97
  • 704
  • 746
Arthur
  • 81
  • 1
  • 1
  • 7

4 Answers4

3

Just slice the columns:

arr1_sliced = arr1[:,1::2]
# if arr1 is a python list, use 
arr1_sliced = np.array(arr1)[:,1::2]

print(arr1_sliced)

# [[ 2  4]
#  [ 7  9]
#  [12 14]]
cs95
  • 379,657
  • 97
  • 704
  • 746
b-fg
  • 3,959
  • 2
  • 28
  • 44
  • What is that trick with comma in the slice? Have never seen that syntax – go2nirvana Nov 02 '20 at 11:15
  • 3
    @go2nirvana It's not a trick, it's [numpy slicing syntax](https://numpy.org/doc/stable/reference/arrays.indexing.html), don't expect to use this in pure python code. This answer makes the implicit assumption that `arr1` is already a numpy array. – cs95 Nov 02 '20 at 11:16
0
arr1 = [[1, 2, 3, 4, 5],
       [6, 7, 8, 9, 10],
       [11, 12, 13, 14, 15]]

[a[1::2] for a in arr1]

You have a list of lists, not an array. Anyhow, i) list comprehension to look at each list in your list of lists. ii) the 2 in 1::2 gives a stride of 2, i.e., every second element. iii) the 1 in 1::2 means that we start at the second (i.e. 1 in 0-based index) element, which it appears you want

innisfree
  • 2,044
  • 1
  • 14
  • 24
0

arr1 is just a syntax error from my point of view. if you meant

arr1 = [[1, 2, 3, 4, 5],
       [6, 7, 8, 9, 10],
       [11, 12, 13, 14, 15]]

A solution might be:

arr2 = [element[1::2] for element in arr1]

arr2 prints out:

>>> arr2
[[2, 4], [7, 9], [12, 14]]
>>> 
the-veloper
  • 304
  • 1
  • 7
0

If you want to use the NumPy function you can use a relevant filter like:

import numpy as np
filter_arr = []

# go through each element in arr
for element in arr:
  # if the element is completely divisble by 2, set the value to True, otherwise False
  if element % 2 == 0:
    filter_arr.append(True)
  else:
    filter_arr.append(False)

Then apply the filter on your data:

arr = np.array([1, 2, 3, 4, 5, 6, 7])
newarr = arr[filter_arr] 
print(filter_arr)
print(newarr)

This example is taken from here.

Yanirmr
  • 923
  • 8
  • 25