欢迎访问我的个人Blog: zengzeyu.com
新建Numpy结构型数据:
import numpy as np student = np.dtype([('name','S20'), ('age',np.int8), ('marks', np.float4)])
a = np.array([('abc', 21, 50),('xyz', 18, 75)], dtype = student)
print a
#输出
[('abc', 21, 50.0), ('xyz', 18, 75.0)]
其中,string
类型数据用S20
表示(20
可更改),其余数据类型如np.int8
和np.float4
均有内建数据表示。
Numpy数组属性:
调整数组大小
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
b = a.reshape(3,2)
print b
#输出
[[1, 2]
[3, 4]
[5, 6]]
三维数组
# 一维数组
import numpy as np
a = np.arange(24) a.ndim
# 现在调整其大小
# 2*4*3: 2个二维数组,每个数组大小4*3
b = a.reshape(2,4,3)
print b
#输出
# b 现在拥有三个维度
[[[ 0, 1, 2]
[ 3, 4, 5]
[ 6, 7, 8]
[ 9, 10, 11]]
[[12, 13, 14]
[15, 16, 17]
[18, 19, 20]
[21, 22, 23]]]
Numpy 来自现有数据的数组
# 将列表转换为 ndarray
import numpy as np
x = [1,2,3]
a = np.asarray(x)
print a
#输出
[1 2 3]
# 来自元组的 ndarray
import numpy as np
x = (1,2,3)
a = np.asarray(x)
print a
#输出
[1 2 3]
Numpy-frombuffer
import numpy as np
s = 'Hello World'
a = np.frombuffer(s, dtype = 'S1')
print a
#输出
['H' 'e' 'l' 'l' 'o' ' ' 'W' 'o' 'r' 'l' 'd']
Numpy-切片和索引
基本切片是 Python 中基本切片概念到 n 维的扩展。 通过将start
,stop
和step
参数提供给内置的slice
函数来构造一个 Python slice
对象。 此slice
对象被传递给数组来提取数组的一部分。
import numpy as np
a = np.arange(10)
s = slice(2,7,1) # 2返回值为2的索引,7返回值为7的索引,1为步长
print a[s]
#输出
[2 3 4 5 6]
在上面的例子中,ndarray
对象由arange()
函数创建。 然后,分别用起始,终止和步长值2
,7
和2
定义切片对象。 当这个切片对象传递给ndarray
时,会对它的一部分进行切片,从索引2
到7
,步长为2
。
NumPy - 数组上的迭代
import numpy as np
a = np.arange(0,60,5)
a = a.reshape(3,4)
print '原始数组是:'
print a print '\n'
print '修改后的数组是:'
for x in np.nditer(a):
print x
#输出
原始数组是:
[[ 0 5 10 15]
[20 25 30 35]
[40 45 50 55]]
修改后的数组是:
0 5 10 15 20 25 30 35 40 45 50 55
注意:迭代的顺序匹配数组的内容布局,而不考虑特定的排序。 这可以通过迭代上述数组的转置来看到。
import numpy as np
a = np.arange(0,60,5)
a = a.reshape(3,4)
print '原始数组是:'
print a print '\n'
print '原始数组的转置是:'
b = a.T
print b
print '\n' print '修改后的数组是:'
for x in np.nditer(b):
print x,
#输出
原始数组是:
[[ 0 5 10 15]
[20 25 30 35]
[40 45 50 55]]
原始数组的转置是:
[[ 0 20 40]
[ 5 25 45]
[10 30 50]
[15 35 55]]
修改后的数组是:
0 5 10 15 20 25 30 35 40 45 50 55
numpy.ndarray.flatten
该函数返回折叠为一维的数组副本,函数接受下列参数:
ndarray.flatten(order)
其中:
- order:
C
-- 按行,F
-- 按列,A
-- 原顺序,k
-- 元素在内存中的出现顺序。