1

How do I insert a single element into an array on numpy. I know how to insert an entire column or row using the insert and axis parameter. But how do I insert/expand by one.

For example, say I have an array:

1 1 1
1 1 1
1 1 1

How do I insert 0 (on the same row), say on (1, 1) location, say:

1 1 1
1 0 1 1
1 1 1

is this doable? If so, then how do you do the opposite (on the same column), say:

1 1 1
1 0 1
1 1 1
  1
user1179317
  • 2,693
  • 3
  • 34
  • 62
  • 2
    Those things you want to create don't look like matrices to me. – Scott Hunter Sep 22 '16 at 13:10
  • ok I guess you could say its arrays – user1179317 Sep 22 '16 at 13:20
  • 1
    What are you _trying_ to do --- as in, what's your overall objective? Odds are, either your goal is not helped by a messy data structure like that, or it _is_ and NumPy is not the right tool for the job. (But I'm willing to be surprised.) – Kevin J. Chase Sep 22 '16 at 13:31
  • You can't. Numpy arrays are not designed for those irregular sizes. Well, maybe you could get something to work for you using arrays of type `object` (see @AmiTavory's answer), but they can introduce other problems. – Warren Weckesser Sep 22 '16 at 13:38
  • I am actually using objects in the arrays. If the array cannot be irregular, then I guess I can pad null/none on the ends to keep it as a regular size. – user1179317 Sep 22 '16 at 14:16
  • 1
    Here's a related one, if you are willing to pad with `None`, etc. : http://stackoverflow.com/questions/38619143/convert-python-sequence-to-numpy-array-filling-missing-values – Divakar Sep 22 '16 at 14:40

2 Answers2

3

Numpy has something that looks like ragged arrays, but those are arrays of objects, and probably not what you want. Note the difference in the following:

In [27]: np.array([[1, 2], [3]])
Out[27]: array([[1, 2], [3]], dtype=object)

In [28]: np.array([[1, 2], [3, 4]])
Out[28]:
array([[1, 2],
       [3, 4]])

If you want to insert v into row/column i/j, you can do so by padding the other rows. This is easy to do:

In [29]: a = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]])

In [30]: i, j, v = 1, 1, 3

In [31]: np.array([np.append(a[i_], [0]) if i_ != i else np.insert(a[i_], j, v) for i_ in range(a.shape[1])])
Out[31]:
array([[1, 1, 1, 0],
       [1, 3, 1, 1],
       [1, 1, 1, 0]])

To pad along columns, not rows, first transpose a, then perform this operation, then transpose again.

Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
-1

I think you should use append() of regular Python arrays (not numpy) Here is a short example

A = [[1,1,1],
     [1,1,1],
     [1,1,1]]
A[1].append(1)

The result is

[[1, 1, 1], 
 [1, 1, 1, 1], 
 [1, 1, 1]]   # like in your example

Column extension with one element is impossible, because values are stored by rows. Thechnically you can do something like this A.append([None,1,None]), but this is bad practice.

Sergey
  • 487
  • 3
  • 7