ValueError: could not broadcast input array from shape (3) into shape (2) simple solution

Viewed 5890

I have this np array and trying to add a number to one of just one of lines(trying to make asymmetric array if possible and if not a 100*3 array is also ok)

a=np.arange(100*2).reshape(-1,2)
a[40]=np.append(a[40],6)

note that a=np.arange(100*2).reshape(-1,2) is just simplified example and not real code that I wanna manipulate. and I receive this error

ValueError: could not broadcast input array from shape (3) into shape (2)

is there any simple solution(except making new array and filling it with loop with previous value then adding 6)?

2 Answers

Would that be a solution to your problem?

import numpy as np

a = np.zeros((100, 3))
a[:,0:2] = np.arange(100*2).reshape(-1,2)

a[40,2]=6

The closest thing in numpy to a ragged array is an object dtype array:

In [475]: a = np.empty(2, object)                                                                    
In [476]: a                                                                                          
Out[476]: array([None, None], dtype=object)

If an element is a list, you can use its append to add a value:

In [477]: a[0] = [1,2]                                                                               
In [478]: a[1] = [2,3]                                                                               
In [479]: a[1].append(4)                                                                             
In [480]: a                                                                                          
Out[480]: array([list([1, 2]), list([2, 3, 4])], dtype=object)

But it's questionable whether such an array is any better that a list

In [481]: a.tolist()                                                                                 
Out[481]: [[1, 2], [2, 3, 4]]
Related