Scientific computing, data analysis basic library learning-NumPy

NumPy provides a powerful multi-dimensional array object ndarray.

1. Create an array
1. Use numpy's built-in array function to create an array

    arr1 = np.array([1,2,3])
    print("创建一维数组",arr1)
    arr2 = np.array([["a","b","c"],[1,1,1]])
    print("创建二维数组",arr2)

2. Use the arange function to create an array
arange(a,b,c) (a: start, b: end c: step)
1) The first element of the array returned by the arange function is 0 by default, and the end element is before the specified value A value minus 1 (ie [0,b) or [0,b-1])
2) The step size represents the difference between two adjacent elements

    #2.使用arange函数创建数组
    arr3 = np.arange(5)
    print("创建5以内的以为数组",arr3)
    arr4 = np.arange(2,10,2)
    print("创建10以内的偶数数组",arr4)

Insert picture description here
3. All 0zero() function, all 1ones() function to create an array
1) All 0 array

    #3.创建一维,二维全0数组
    z0 = np.zeros(10)
    print("一维全0数组,10个元素",z0)
    z1 = np.zeros((3,4))
    print("创建3行4个元素的全0数组",z1)

Insert picture description here2) All 1 array

    #4.创建一维,二维全1数组
    o0 = np.ones(10)
    print("一维全1数组,10个元素",o0)
    o1 = np.ones((3,4))
    print("创建3行4个元素的全1数组",o1)

Insert picture description here

Second, the attributes and methods of the
array 1. View the size of each dimension of the array shape()

    o1 = np.ones((3,4))
    print("创建3行4个元素的全1数组",o1)

    #二、数组的属性方法
    print("查看变量各个维度的大小",o1.shape)
    print("查看变量第一维度的大小", o1.shape[0])
    print("查看变量第二维度的大小", o1.shape[1])

Insert picture description here
***Numpy automatically recognizes the element type as shown in the figure below:

print(np.array(["zhongguo","meiguo"]).dtype)

Insert picture description here
"<U8" means that the string does not exceed 8

2. View the type dtype of the elements in the array and the type conversion function astype()

    print("查看数组元素类型",o1.dtype)
    #类型转换函数astype(欲转换的类型),返回一个新数组,原数组元素类型不变
    o1_1 = o1.astype(np.int32)
    print("查看新数组元素类型", o1_1.dtype)
    print("查看数组元素类型", o1.dtype)

Insert picture description here
When the float type is converted to an integer array, the decimal part will be cut off

    arr_string = np.array(["12.45","23.78","3.98"])
    arr_float = arr_string.astype(np.float64)
    print(arr_float)
    arr_int = arr_float.astype(np.int32)
    print(arr_int)

Insert picture description here
Juoyter notebook shortcut keys to quickly execute code:
click the mouse to select the code box to be specified, the
shift+enter combination key directly executes all the codes in the code box; the
Alt+enter combination key executes the code in the code box, and it is below the code box Add another empty code box.

Guess you like

Origin blog.csdn.net/qq_44801116/article/details/110143866