Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append a "label" to a numpy array

Tags:

python

numpy

I have a numpy array created such as:

x = np.array([[1,2,3,4],[5,6,7,8]])
y = np.asarray([x])

which prints out

  x=[[1 2 3 4]
     [5 6 7 8]]

  y=[[[1 2 3 4]
     [5 6 7 8]]]

What I would like is an array such as

[0 [[1 2 3 4]
  [5 6 7 8]]]

What's the easiest way to go about this?

Thanks!

like image 818
jwsmithers Avatar asked Jun 15 '26 09:06

jwsmithers


1 Answers

To do what you're asking, just use the phrase

labeledArray = [0, x]

This way, you will get a standard list with 0 as the first element and a Numpy array as the second element.

However, in practice, you are probably trying to label for the purpose of later recall. In that case, I'd recommend you use a dictionary, as it is less confusing to keep track of:

myArrays = {}
myArrays[0] = x

Which can be used as follows:

>>> myArrays
{0: array([[1, 2, 3, 4],
   [5, 6, 7, 8]])}
>>> myArrays[0]
array([[1, 2, 3, 4],
   [5, 6, 7, 8]])
like image 126
Naveen Arun Avatar answered Jun 16 '26 23:06

Naveen Arun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!