1、NumPy 数据类型
https://www.runoob.com/numpy/numpy-dtype.html
int8、uint8、int16、uint16、int32、uint32、int64、uint64、float16、float32、float64等
numpy.float32转float等
import numpy as np
# examples using a.item()
type(np.float32(0).item()) # <type 'float'>
type(np.float64(0).item()) # <type 'float'>
type(np.uint32(0).item()) # <type 'long'>
# examples using np.asscalar(a)
type(np.asscalar(np.int16(0))) # <type 'int'>
type(np.asscalar(np.cfloat(0))) # <type 'complex'>
type(np.asscalar(np.datetime64(0))) # <type 'datetime.datetime'>
type(np.asscalar(np.timedelta64(0))) # <type 'datetime.timedelta'>
float为float64,有时文件太大,内存不够,需float64转float32
np.array(grid, dtype=np.float32)
numpy.uint8转numpy.float32
.astype('float32')
基本操作
1、插入、排序
np.append(level_h400,800) # 插入800
np.append(level_h400,[800,900]) # 插入800、900
np.sort(level_h400) # 排序
np排序
a = np.array([1, 2, 4, 3, 5, 6])
b = a[::-1] #倒序
f = np.flipud(a) #倒序
print(f)
print(b)
c = np.array([5, 4, 3, 9,10, 6])
e = np.sort(c) #正序
print(e)
2、创建等差数列np.linspace
x = np.linspace(-1348.73,1348.27,900)
y = np.linspace(-1200.2,1199.8,801)
3、reshape(行,列)
lon = np.array(lon).reshape(-1,1)
#只显示1列,若只需要指定行数,那么列数直接用-1代替就行,计算机帮我们算有多少列,反之亦然
4、数组拼接np.concatenate
https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.concatenate.html
>>> a = np.array([[1, 2], [3, 4]])
>>> b = np.array([[5, 6]])
>>> np.concatenate((a, b), axis=0)
array([[1, 2],
[3, 4],
[5, 6]])
>>> np.concatenate((a, b.T), axis=1)
array([[1, 2, 5],
[3, 4, 6]])
>>> np.concatenate((a, b), axis=None)
array([1, 2, 3, 4, 5, 6])
>>> a=np.array([[1,2,3],[4,5,6]])
>>> b=np.array([[11,21,31],[7,8,9]])
>>> np.concatenate((a,b),axis=1) #axis=1表示对应行的数组进行拼接
array([[ 1, 2, 3, 11, 21, 31],
[ 4, 5, 6, 7, 8, 9]])
5、arange函数创建等差数组
np.arange([start, ]stop, [step, ]dtype=None)
start:可忽略不写,默认从0开始;起始值
stop:结束值;生成的元素不包括结束值
step:可忽略不写,默认步长为1;步长
dtype:默认为None,设置显示元素的数据类型
x = np.arange(0, 10)
[0 1 2 3 4 5 6 7 8 9]
xnew = np.arange(0, 9, 0.1)
[0. 0.1 0.2 0.3 0.4....8.6 8.7 8.8 8.9]
可以对生成的等差一维数组,进行重塑,使用reshape(行,列)
注意:arange容易出问题
lon = np.arange(108.8, 116, 0.03) # len(lon) = 241 [108.8 108.83 .... 115.97 116. ]
lat = np.arange(37, 28.27, -0.03) # len(lat) = 291 [37. 36.97 ..... 28.33 28.3 ]
建议使用linspace
lon = np.linspace(108.8, 116, 241) # 241
lat = np.linspace(37, 28.3, 291) # 291
6、numpy.ndarray
# datetime64[ns]
tl = dat.time.dt.strftime('%Y%m%d%H%M%S')
# array('20200225180000', dtype=object) 维度是0的数组,没有下标可用
# 转str
str(arr)
tl.values.tolist()
7、获取数组最近点
# t为数组,x为某个值,返回x在数组t中最近的值
def near_point(t, x):
ind = np.searchsorted(t, x)
ind = min(len(t)-1, ind)
ind = max(1, ind)
if x < (t[ind-1] + t[ind]) / 2.0:
ind = ind-1
return ind
8、初始化numpy.zeros(shape, dtype=float, order=‘C’)
https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.zeros.html
返回给定形状和类型的新数组,并用零填充。
data = np.zeros([360,168,201])
print(data.shape)
# <class 'tuple'>: (360, 168, 201)
# 初始化数组 111*222
data_d_all = np.zeros(shape=(111,222))
9、numpy数组属性
https://www.runoob.com/numpy/numpy-array-attributes.html
1、ndarray.shape
https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.ndarray.shape.html
数组的维度,对于矩阵,n 行 m 列,如标题8
lat.shape[0]
#一维数组的长度 或 二维数组的第一维 或三维数组的第一维等
2、ndarray.ndim
维度的数量
data = np.zeros([360,168,201])
print(data.ndim)
# 3
3、ndarray.size
数组元素的总个数,相当于 .shape 中 n*m 的值
4、ndarray.dtype
ndarray对象的元素类型
5、ndarray.itemsize
ndarray对象中每个元素的大小,以字节为单位
6、ndarray.flags
ndarray对象的内存信息
7、ndarray.real
ndarray元素的实部
8、ndarray.imag
ndarray元素的虚部
9、ndarray.data
包含实际数组元素的缓冲区,由于一般通过数组的索引获取元素,所以通常不需要使用这个属性。
10、numpy.meshgrid(lon, lat)
生成网格点坐标矩阵
11、ndarray.ravel()
https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.ndarray.ravel.html
将多维数组降位一维,ravel()返回的是视图(view,也颇有几分C/C++引用reference的意味),会影响(reflects)原始矩阵
lon_ravel = lon.ravel()
# lon <class 'tuple'>: (360, 480)
#lon_ravel <class 'tuple'>: (172800,)
由二维数组变为一维数组([[x,x,x],[x,x,x]...] --> [x,x,x...])
12、ndarray.T 转置矩阵
lat_t = lat.T
# lat <class 'tuple'>: (360, 480)
# lat_t <class 'tuple'>: (480, 360)
13、np.newaxis
np.newaxis的功能:插入新维度
x1 = np.array([1, 2, 3, 4, 5])
print(x1) # [1 2 3 4 5]
x1_new = x1[:, np.newaxis]
print(x1_new)
# [[1]
# [2]
# [3]
# [4]
# [5]]
x1_new = x1[np.newaxis, :]
print(x1_new) # [[1 2 3 4 5]]
arr = np.arange(5 * 5).reshape(5, 5)
print(arr) # 二维
arr_3D = arr[np.newaxis, ...]
print(arr_3D) # 三维
14、np数组批量替换某值
import numpy as np
a = np.array([[1,2,0],[4,0,1],[0,5,0]])
a[a==9999] = np.NAN
print(a)
15、mean函数,根据制定轴方向计算算术平均值。
numpy.mean( a, axis=None, dtype=None, out=None, keepdims=<no value>)
返回数组元素的平均值。默认情况下,平均值从平展开的数组计算得出,如果有指定轴,根据指定轴方向计算得出。整数输入的中间值和返回值也都是float64
参数
1. a : array_like
需要计算均值的数组。如果a不是一个数组,则会尝试进行转换。
2. axis : None or int or tuple of ints, optional
指定计算均值方向的轴。默认是在展开后的数组上计算。
1.7.0新版本功能
如果这是一个整数元组,则均值是在多个轴上计算,而不是之前的单个轴或者所有轴。
3. dtype : data-type, optional
输出均值的类型。 对于整数输入,默认值为float64; 对于浮点数输入,它与输入类型相同。
4. out : ndarray, optional
存放结果的备选输出数组。默认是None;如果提供了,它必须跟期望输出有相同的shape,但必要时 将转换类型。更多细节请看doc.ufuncs。
>>> a = np.array([[1, 2], [3, 4]])
>>> np.mean(a)
2.5
>>> np.mean(a, axis=0)
array([2., 3.])
>>> np.mean(a, axis=1)
array([1.5, 3.5])
16、最大值和最小值
#排除掉nan后计算最大值最小值
max = np.nanmax(data)
min = np.nanmin(data)
17、判断是否为nan
if bool(1-np.isnan(v)):
18、np降维
>>> from numpy import *
>>> a=array([[1,2],[3,4],[5,6]])
>>> a
array([[1, 2],
[3, 4],
[5, 6]])
>>> a.flatten() #默认按行的方向降维
array([1, 2, 3, 4, 5, 6])
>>> a.flatten('F') #按列降维
array([1, 3, 5, 2, 4, 6])
>>> a.flatten('A') #按行降维
array([1, 2, 3, 4, 5, 6])
>>>
19、np稀疏
data[::10, ::10] #二维稀疏10
lat[::10] #一维稀疏10
20、查询元素索引
index = int(np.where(yb_time_list==yb_time)[0])
21、np转txt
s = 'diamond 4 mqpf_20201118_0500.nc\r' \
'2020 11 18 05 00 25 0.01 0.01 113.22 124.28 33.62 38.98 1107 537 5 10 80 1.00 0.00\r'
np.savetxt(file_name, data_all, fmt='%s', header=s, delimiter=' ', newline='\r',
comments='')