Creation of NumPy array

1, NumPy create array

In addition to using the underlying ndarray constructor, the ndarray array can also be created in the following ways.

1.numpy.empty

numpy. The empty method is used to create an uninitialized array with a specified shape and data type:

numpy.empty(shape, dtype = float, order = 'C')

 

shape Array shape
dtype Data type, optional
order There are "C" and "F" options, representing row priority and column priority respectively, and the order of storage elements in computer memory.

 

Demo code:

import numpy as np 
x = np.empty([3,2], dtype = int) 
print (x)

Output results:

[[1632772128 1936028521]
 [ 538976266  757935392]
 [ 170732845  538976288]]

 

Demo code:

x = np.empty([1,1], dtype = int) 
print (x[0][0])

Output results:

1970086003

Note: array elements are random values because they are not initialized.

2.numpy.zeros

Create an array of the specified size, and the array elements are filled with 0:

numpy.zeros(shape, dtype = float, order = 'C')

Demo code:

# Floating point number by default
x = np.zeros(5) 
print('x:',x)
 
# Set type to integer
y = np.zeros((5,), dtype = int) 
print('y:',y)
 
# Custom type
z = np.zeros((2,3), dtype = [('x', 'float'), ('y', 'i4')])  
print('z:',z)

Output results:

x: [0. 0. 0. 0. 0.]
y: [0 0 0 0 0]
z: [[(0., 0) (0., 0) (0., 0)]
 [(0., 0) (0., 0) (0., 0)]]

3.numpy.ones

Create an array of the specified shape, and the array elements are filled with 1:

numpy.ones(shape, dtype = None, order = 'C')

Demo code:

# Floating point number by default
x = np.ones(5) 
print(x)
 
# Custom type
x = np.ones((2,3), dtype = [('x', 'float'), ('y', 'i4')])  
print(x)

Output results:

[1. 1. 1. 1. 1.]
[[(1., 1) (1., 1) (1., 1)]
 [(1., 1) (1., 1) (1., 1)]]

 

2, Create an array from an existing array

1.numpy.asarray

numpy.asarray is similar to numpy Array, but numpy Asarray has only three parameters, which is better than numpy Array is two less.

numpy.asarray(a, dtype = None, order = None)

 

parameterdescribe
a Any form of input parameters can be, list, tuple of list, tuple, tuple of tuple, list of tuples, multidimensional array
dtype Data type, optional
order Optional, there are "C" and "F" options, representing row priority and column priority respectively, and the order of storage elements in the computer memory.

 

Demo code:

# Convert list to ndarray
x =  [1,2,3] 
a = np.asarray(x)  
print(a)

# Convert tuples to ndarray
x = (1,2,3)
a = np.asarray(x)
print(a)

# Convert tuple list to ndarray
x = [(1,2,3),(4,5)]
a = np.asarray(x)
print (a)

Output results:

[1 2 3]
[1 2 3]
[(1, 2, 3) (4, 5)]

 

Code demonstration:

# set up dtype parameter
x =  [1,2,3] 
a = np.asarray(x, dtype =  float)  
print (a)

Output results:

[1. 2. 3.]

2.numpy.frombuffer

numpy.frombuffer is used to implement dynamic arrays.

numpy.frombuffer accepts the buffer input parameter, reads it in the form of a stream, and converts it into an ndarray object.

numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0)

Note: when buffer is a string, Python3 defaults to STR of Unicode type, so it should be converted to bytestring and added b before the original str.

 

parameterdescribe
buffer It can be any object and will be read in as a stream.
dtype Return the data type of the array, optional
count The number of data read, which defaults to -1, reads all data.
offset The starting position of reading, which is 0 by default.

 

Demo code:

s =  b'Hello World' 
a = np.frombuffer(s, dtype =  'S1')  
print (a)

Output results:

[b'H' b'e' b'l' b'l' b'o' b' ' b'W' b'o' b'r' b'l' b'd']

3.numpy.fromiter

numpy. The fromiter method creates an ndarray object from an iteratable object and returns a one-dimensional array.

numpy.fromiter(iterable, dtype, count=-1)

Demo code:

# use range Function to create a list object  
list=range(5)
it=iter(list)
 
# Create using iterators ndarray 
x=np.fromiter(it, dtype=float)
print(x)

Output results:

[0. 1. 2. 3. 4.]

 

3, Create an array from a numeric range

1.numpy.arange

In the numpy package, use the range function to create a numerical range and return the ndarray object. The function format is as follows:

numpy.arange(start, stop, step, dtype)

 

parameterdescribe
start The starting value is 0 by default
stop End value (not included)
step Step size, default to 1
dtype Returns the data type of ndarray. If it is not provided, the type of input data will be used.

 

Demo code:

# Build 0-5 Array of
x = np.arange(5)  
print (x)

# set up dtype,Start value, end value and step size
x = np.arange(10,20,2,dtype = float)
print (x)

Output results:

[0  1  2  3  4]
[10. 12. 14. 16. 18.]

2.numpy.linspace

numpy. The linspace function is used to create a one-dimensional array, which is composed of an arithmetic sequence. The format is as follows:

np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)

 

parameterdescribe
start Starting value of the sequence
stop The ending value of the sequence. If the endpoint is true, the value is included in the sequence
num The number of equal step samples to be generated, which defaults to 50
endpoint When the value is true, the number sequence contains the stop value, otherwise it does not, and the default is true.
retstep If True, the spacing will be displayed in the generated array, otherwise it will not be displayed.
dtype Data type of ndarray

 

Demo code:

# Set the starting point as 1, the ending point as 10, and the number of series as 4
a = np.linspace(1,10,4)
print(a)

# take endpoint Set as false,Does not contain end value
a = np.linspace(10, 20, 5, endpoint = False)
print(a)

# Set spacing
a =np.linspace(1,10,10,retstep= True)
print(a)

# Expand examples
b =np.linspace(1,10,10).reshape([10,1])
print(b)

Output results:

[ 1.  4.  7. 10.]
[10. 12. 14. 16. 18.]
(array([ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10.]), 1.0)
[[ 1.]
 [ 2.]
 [ 3.]
 [ 4.]
 [ 5.]
 [ 6.]
 [ 7.]
 [ 8.]
 [ 9.]
 [10.]]

3.numpy.logspace

numpy. The logspace function is used to create an equal ratio sequence. The format is as follows:

np.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)

 

parameterdescribe
start The starting value of the sequence is: base ** start
stop The ending value of the sequence is: base ** stop. If endpoint is true, the value is included in the sequence
num The number of equal step samples to be generated, which defaults to 50
endpoint When this value is true, the number sequence contains the stop value, otherwise it does not. The default is true.
base Base of log.
dtype Data type of ndarray

Demo code:

# The default base is 10
a = np.logspace(1.0, 2.0, num = 4)
print (a)

# Set the base of the logarithm to 2
a = np.logspace(0,9,num=10,base=2,dtype='int')
print (a)

Output results:

[ 10.          21.5443469   46.41588834 100.        ]
[  1   2   4   8  16  32  64 128 256 512]

 

Tags: Python

Posted by lutzlutz896 on Sun, 31 Jul 2022 21:39:53 +0300