3

I am learning python and I am having a little bit of trouble while handling an object. I have tried to look for a solution but it led nowhere, so I am asking you guys.

I want to get the first X columns of an object, but I can't as it doesn't have the same size in every row.

I have this object:

array([[45, 45, 45, 50, 51, 50, 50, 50, 51, 50, 52],
       [45, 45, 45, 50, 51, 50, 50, 50, 51, 50, 51, 52, 55],
       [45, 45, 45, 50, 51, 50, 52, 50, 50, 50, 51],
       [50, 51, 52, 55, 50, 52, 50, 50, 50, 51, 50, 51]], dtype=object)

And I would like to get something like this:

array([[45, 45, 45, 50],
       [45, 45, 45, 50],
       [45, 45, 45, 50],
       [50, 51, 52, 55]])

What could I do to solve this? Thanks for your help

Alvaro

1
  • 1
    You have a 1d 4 element array of dtype=object. Each element is a list. This is basically the same as a list of lists; and it's usually best to treat it as such. The array wrapper does not add much, and may even slow things down. Commented Oct 29, 2016 at 17:33

2 Answers 2

3

What about

import numpy as np
data = np.array([[45, 45, 45, 50, 51, 50, 50, 50, 51, 50, 52],
                 [45, 45, 45, 50, 51, 50, 50, 50, 51, 50, 51, 52, 55],
                 [45, 45, 45, 50, 51, 50, 52, 50, 50, 50, 51],
                 [50, 51, 52, 55, 50, 52, 50, 50, 50, 51, 50, 51]], dtype=object)
newData = np.array([d[:4] for d in data])
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that works! Do you think there is any way to do it without a for? For example like an array function or something like that?
0

You may need a more generic solution where you can also specifiy the number of rows as follows:

import numpy as np

arr = np.array([[45, 45, 45, 50, 51, 50, 50, 50, 51, 50, 52],
       [45, 45, 45, 50, 51, 50, 50, 50, 51, 50, 51, 52, 55],
       [45, 45, 45, 50, 51, 50, 52, 50, 50, 50, 51],
       [50, 51, 52, 55, 50, 52, 50, 50, 50, 51, 50, 51]], dtype=object)

def slice_array(arr, num_cols, num_rows=None):
    if num_rows:
        return np.array([row[:num_cols] for row in arr[:num_rows]])
    return np.array([row[:num_cols] for row in arr])

res1 = slice_array(arr, 4, 2)
res2 = slice_array(arr, 4)  # Like in your case

Results:

>>> res1
array([[45, 45, 45, 50],
       [45, 45, 45, 50]])
>>> res2
array([[45, 45, 45, 50],
       [45, 45, 45, 50],
       [45, 45, 45, 50],
       [50, 51, 52, 55]])

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.