전세영
전세영

Reputation: 11

Python How to make array in array?

I have a numpy array Z1, Z2, Z3:
    Z1 = [1,2,3]
    Z2 = [4,5]
    Z3 = [6,7,8,9]
I want new numpy array Z that have Z1, Z2, Z3 as array like:
    Z = [[1,2,3],[4,5],[6,7,8,9]
    print(type(Z),type(Z[0]))
    >>> <class 'numpy.ndarray'> <class 'numpy.ndarray'>
I used np.append, hstack, vstack, insert, concatenate ...but all I failed.
There is only 2 case:
    Z = [1,2,3,4,5,6,7,8,9]
or ERROR
so I made a list Z first, and append list Z1, Z2, Z3 and then convert list Z into numpy array Z.
BUT
    Z = [[1,2,3],[4,5],[6,7,8,9]]
    print(type(Z),type(Z[0]))
    >>> <class 'numpy.ndarray'> <class 'list'>

I want to do not use 'while' or 'for'. Help me please..

Upvotes: 1

Views: 1606

Answers (4)

전세영
전세영

Reputation: 11

everybody thanks! Answers are a little bit different with that I want, but eventually I solve that without use 'for' or 'while'.

First, I made "numpy array" Z1, Z2, Z3 and put them into "list" Z. There are array in List.

Second, I convert "list" Z into "numpy array" Z. It is array in array that I want.

Upvotes: 0

hpaulj
hpaulj

Reputation: 231385

First, Z is a list of lists:

In [33]: Z = [[1,2,3], [4,5], [6,7,8,9]]

This is an array of lists - note the dtype. But keep in mind that np.array([[1,2,3],[4,5,6]]) will produce a 2d array of dtype int.

In [34]: np.array(Z)
Out[34]: array([[1, 2, 3], [4, 5], [6, 7, 8, 9]], dtype=object)

The surest way of creating an array of object dtype, and given shape is to initialize it, and then fill it:

In [35]: out = np.zeros((3,), dtype=object)
In [36]: out[...] = Z
In [37]: out
Out[37]: array([[1, 2, 3], [4, 5], [6, 7, 8, 9]], dtype=object)

Again this is an array of lists. To make an array of arrays, we first have to make a list of arrays:

In [38]: out[...] = [np.array(x) for x in Z]
In [39]: out
Out[39]: array([array([1, 2, 3]), array([4, 5]), array([6, 7, 8, 9])], dtype=object)

Object arrays are awkward beasts, not quite lists and not quite (regular) arrays.

Upvotes: 1

Stijn Van Daele
Stijn Van Daele

Reputation: 295

Try

import numpy as np

Z1 = [1,2,3]
Z2 = [4,5]
Z3 = [6,7,8,9]

Z = np.array([Z1, Z2, Z3])
print(Z)
print(type(Z))

This will convert your list of lists into an numpy array

Upvotes: 1

blue note
blue note

Reputation: 29081

You can't make that array. Arrays is numpy are similar to matrices in math. They have to be mrows, each having n columns. Use a list of lists, or list of np.arrays

Upvotes: 0

Related Questions