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]]

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.