numpy(一)

1.基础

Numpy库里最重要的数组对象,叫做narray,是一个通用的同构数据多维容器,和C语言里的多维数组类似。这个narray容器里所有类型即dtype必须保持一致,可以有int32,float64等,每一个narray容器都有一个shape(表示narray的维度)。另外还有许多关于narray的内置函数,在下面代码里意义进行解释说明。

#!/usr/bin/python
import numpy as np

#创建一个narray类型arange(0,6)和range,0,6)一样,不包含尾的
a = np.array([[0,1,2],[3,4,5]])
#或者a = np.arange(0,6).reshape(2,3)
print(a)
print(type(a))

'''
#结果
[[0 1 2]
 [3 4 5]]
<class 'numpy.ndarray'>
'''

#a的维度
a_ndim = a.ndim
print(a_ndim)
'''
#结果
6
'''

#a的大小,表示a中一共有多少个元素
a_size = a.size
print(a_size)
'''
#结果
6
'''

#a的形状
a_shape = a.shape
print(a_shape)
'''
#结果
(2,3)
'''

#a里面元素类型
a_type = a.dtype
print(a_type)
'''
#结果
int64
'''

2.从python原生的list或和tuple中创建narray

#!/usr/bin/python
import numpy as np

b = np.array([0,1,2])
print(b)
#b的类型
print(type(b))
#b中元素的类型
print(b.dtype)
'''
#结果
[0 1 2]
<class 'numpy.ndarray'>
int64
'''

c = np.array([0.0,1.0,2.0])
print(c)
#c的类型
print(type(c))
#c中元素的类型
print(c.dtype)
'''
#结果
[0. 1. 2.]
<class 'numpy.ndarray'>
float64
'''
#也可以用元组来创建
d = np.array((0,1,2))
#d的类型
print(type(d))
#d中元素的类型
print(d.dtype)
'''
#结果
<class 'numpy.ndarray'>
int64
'''

3.创建二维数组多维数组也是一样的

#!/usr/bin/python
import numpy as np

#注意别忘了加最外层的[]
e=np.array([[1,2,3],[4,5,6]])
print(e)
print(type(e))
print(e.dtype)
'''
#结果
[[1 2 3]
 [4 5 6]]
<class 'numpy.ndarray'>
int64
'''

#也可以直接在里面给它初始化类型
f = np.array([[0,1,2],[3,4,5]],dtype = complex)
print(f)
print(type(f))
print(f.dtype)
'''
#结果
[[0.+0.j 1.+0.j 2.+0.j]
 [3.+0.j 4.+0.j 5.+0.j]]
<class 'numpy.ndarray'>
complex128
'''


#!/usr/bin/python
import numpy as np
#每次输入多个数组复杂
#直接使用类似于range()函数功,在numpy为arange
#还有linespace,可以准确的确定数组的个数

a = np.arange(0,100,10)
print(a)

b = np.linspace(0,2.5,5)
print(b)
'''
#结果
[ 0 10 20 30 40 50 60 70 80 90]
[0.    0.625 1.25  1.875 2.5  ]
'''

4.对数组进行reshape,改变形状,例如3行4列变成2行6列

import numpy as np
a = np.arange(0,12).reshape(3,4)
print('a:')
print(a)
b = a.reshape(2,6)
print('b:')
print(b)

#结果
a:
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
b:
[[ 0  1  2  3  4  5]
 [ 6  7  8  9 10 11]]

import numpy as np
#数组太大numpy自动省略中间部分数字
print(np.arange(2500).reshape(50,50))

#结果
[[   0    1    2 ...   47   48   49]
 [  50   51   52 ...   97   98   99]
 [ 100  101  102 ...  147  148  149]
 ...
 [2350 2351 2352 ... 2397 2398 2399]
 [2400 2401 2402 ... 2447 2448 2449]
 [2450 2451 2452 ... 2497 2498 2499]]



#可以用下面函数强行打印出全部数字
np.set_printoptions(threshold='nan')

 

猜你喜欢

转载自blog.csdn.net/lerry13579/article/details/82119473