import numpy as np
data1 = [6,7,8,9]
arr1 = np.array(data1)
print(arr1)
嵌套序列(比如由一组等长列表组成的列表)将会被转换为一个多维数组:
import numpy as np
data2 = [[1,2,3,4],[5,6,7,8]]
arr2 = np.array(data2)
print(arr2.ndim)
print(arr2.shape)
输出如下所示:
2
(2, 4)
np.array会为这个新建的数组推断出一个较为合适的数据类型。数据类型保存在一个特殊的dtype对象中。
print(arr2.dtype)
输出如下所示:
int64
显示转换类型
float_arr = arr2.astype(np.float64)
print(float_arr.dtype)
输出如下所示:
float64
arr3 = arr2 * 2
print(arr3)
输出如下所示:
[[ 2 4 6 8]
[10 12 14 16]]
import numpy as np
arr = np.arange(10)
print(arr)
print(arr[5:8])
import numpy as np
fruit = np.array(["苹果","香蕉","葡萄","梨子","香蕉"])
print(fruit == "香蕉")
输出如下所示:
[False True False False True]
import numpy as np
data = np.random.randn(5,4)
print(data)
data1 = data[fruit == "香蕉"]
print(data1)
data2 = data[fruit == "香蕉",2:]
print(data2)
输出如下所示:
[[ 0.49075004 1.55862386 1.03066782 0.22563899]
[-0.60533086 -0.36525286 1.14833953 -1.18084883]
[ 0.74664513 1.63439969 -1.55003165 0.12231136]
[-0.22104506 -1.38852615 -0.40339262 0.98258786]
[-0.39505004 2.00589232 -0.64130727 0.24946445]]
[[-0.60533086 -0.36525286 1.14833953 -1.18084883]
[-0.39505004 2.00589232 -0.64130727 0.24946445]]
[[ 1.14833953 -1.18084883]
[-0.64130727 0.24946445]]
import numpy as np
arr = np.arange(15).reshape((3,5))
print(arr)
print(arr.T)
高维数组:
arr = np.arange(16).reshape((2,2,4))
print(arr)
输出如下所示:
[[[ 0 1 2 3]
[ 4 5 6 7]]
[[ 8 9 10 11]
[12 13 14 15]]]