1. numpy.empty
numpy.empty(shape, dtype=float, order='C', *, like=None)
返回一个给定shape和type的新数组,但不初始化entries。
Parameters: shape: int or tuple of int e.g. (2,3) or 2.
dtype: data-type, optional Default is numpy.float64
order: {'C','F'},optional, Default:'C'
row-major(C-style )
column-major(Fortran-style)
like:array_like, optional
Returns: out:ndarray
例: 生成空数组(可做参量初始化)
import numpy as np
a = np.empty(shape=[0, 2])
print(a.shape)
'''
>>> (0,2)
'''
print(a)
'''
>>> []
'''
例: 生成非空数组
a = np.empty(shape=[2, 2])
print(a.shape)
'''
>>> (2,2)
'''
print(a)
'''
>>> [[-1.93601037e+091 7.17958114e-312]
[ 7.17958108e-312 -6.47269325e-165]]
'''
和zeros不同,它不把值设置为0,因此生成可能稍微会快一点。但是,不做初始化可能会造成意外影响,存在风险。
2. numpy.append
numpy.append(arr, values, axis=None)
数组末尾追加值
Parameters: arr: array_like
Values are appended to a copy of this array.
values: array_like
These values are appended to a copy of arr.
axis: int, optional
If axis is not given, both arr and values are flattened before use.
Returns: append: ndarray
例: axis为默认
a = np.append([1, 2, 3], [[4, 5, 6], [7, 8, 9]])
print(a)
'''
>>> [1 2 3 4 5 6 7 8 9]
'''
例: axis =0
a = np.append([[1, 2, 3]], [[4, 5, 6], [7, 8, 9]], axis=0)
print(a)
'''
>>> [[1 2 3]
[4 5 6]
[7 8 9]]
'''
3. np.empty和np.append追加组合
例:行初始化以及行追加
import numpy as np
a = np.empty(shape=(0, 3))
for i in range(5):
values = [i, i ** 2, i + i ** 2]
row_values = np.expand_dims(np.array(values), axis=0)
a = np.append(a, row_values, axis=0)
print(a)
'''
>>>[[ 0. 0. 0.]
[ 1. 1. 2.]
[ 2. 4. 6.]
[ 3. 9. 12.]
[ 4. 16. 20.]]
'''