1

I have a given array that I want to take every 3rd value starting at the 1st value and append it to a new list. I can take the values that I would like but it returns the as a 1 x 28 array. I want it to return as a 4 x 7 array. How can I tell it that when it reaches the end of the first line to start a new line?

Code:

import numpy as np

list = [
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
    [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21],
    [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22],
    [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
]
newlist = []
list = np.array(list)
for row in list:
    k = 0
    for value in row:
        if k % 3 == 0:
            newlist.append(value)
        else:
            pass
        k += 1
newlist = np.array(newlist)
print(newlist)

Output:

[ 1  4  7 10 13 16 19  2  5  8 11 14 17 20  3  6  9 12 15 18 21  4  7 10 13 16 19 22]

Desired output:

[[ 1  4  7 10 13 16 19 ][ 2  5  8 11 14 17 20 ][ 3  6  9 12 15 18 21 ][ 4  7 10 13 16 19 22]]
rzaratx
  • 756
  • 3
  • 9
  • 29

2 Answers2

1

Try using slicing with ::3 with a list comprehension:

l = [
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
    [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21],
    [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22],
    [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
]
print(np.array([i[::3] for i in l]))

To learn more about slicing, look here:

Understanding slice notation

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
1

You should be able to directly index this in bumpy with l[:,::3]:

import numpy as np

l = np.array([
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
    [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21],
    [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22],
    [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
])

l[:,::3]

Result

array([[ 1,  4,  7, 10, 13, 16, 19],
       [ 2,  5,  8, 11, 14, 17, 20],
       [ 3,  6,  9, 12, 15, 18, 21],
       [ 4,  7, 10, 13, 16, 19, 22]])

(also, don't name your variable list)

Mark
  • 90,562
  • 7
  • 108
  • 148