Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate 2d numpy array?

I'm trying to generate a 2d numpy array with the help of generators:

x = [[f(a) for a in g(b)] for b in c]

And if I try to do something like this:

x = np.array([np.array([f(a) for a in g(b)]) for b in c])

I, as expected, get a np.array of np.array. But I want not this, but ndarray, so I can get, for example, column in a way like this:

y = x[:, 1]

So, I'm curious whether there is a way to generate it in such a way.

Of course it is possible with creating npdarray of required size and filling it with required values, but I want a way to do so in a line of code.

like image 787
Taygrim Avatar asked Feb 20 '15 12:02

Taygrim


People also ask

How do I create a 2-dimensional NumPy array?

In Python to declare a new 2-dimensional array we can easily use the combination of arange and reshape() method. The reshape() method is used to shape a numpy array without updating its data and arange() function is used to create a new array.

How do you create an empty 2D NumPy array?

Create an empty 2D Numpy array using numpy.empty() To create an empty 2D Numpy array we can pass the shape of the 2D array ( i.e. row & column count) as a tuple to the empty() function. It returned an empty 2D Numpy Array of 5 rows and 3 columns but all values in this 2D numpy array were not initialized.

How do you create a 2D array in python?

We can insert elements into a 2 D array using the insert() function that specifies the element' index number and location to be inserted. # Write a program to insert the element into the 2D (two dimensional) array of Python. from array import * # import all package related to the array.

What is 2D array in NumPy?

2D array are also called as Matrices which can be represented as collection of rows and columns. In this article, we have explored 2D array in Numpy in Python. NumPy is a library in python adding support for large multidimensional arrays and matrices along with high level mathematical functions to operate these arrays.


1 Answers

To create a new array, it seems numpy.zeros is the way to go

import numpy as np
a = np.zeros(shape=(x, y))

You can also set a datatype to allocate it sensibly

>>> np.zeros(shape=(5,2), dtype=np.uint8)
array([[0, 0],
       [0, 0],
       [0, 0],
       [0, 0],
       [0, 0]], dtype=uint8)
>>> np.zeros(shape=(5,2), dtype="datetime64[ns]")
array([['1970-01-01T00:00:00.000000000', '1970-01-01T00:00:00.000000000'],
       ['1970-01-01T00:00:00.000000000', '1970-01-01T00:00:00.000000000'],
       ['1970-01-01T00:00:00.000000000', '1970-01-01T00:00:00.000000000'],
       ['1970-01-01T00:00:00.000000000', '1970-01-01T00:00:00.000000000'],
       ['1970-01-01T00:00:00.000000000', '1970-01-01T00:00:00.000000000']],
      dtype='datetime64[ns]')

See also

  • How do I create an empty array/matrix in NumPy?
  • np.full(size, 0) vs. np.zeros(size) vs. np.empty()
like image 146
ti7 Avatar answered Nov 02 '22 19:11

ti7