Numpy学习

Numpy学习

np.

np.array()

1
data = np.array([1, 2, 3, 4, 5])

np.random.randint

1
2
3
np_data = np.random.randint(1, 100, size=(4, 3))

np.random.randint(20, 35, 5)

np.random.seed(42)

np.arange(12).reshape(3,4)

np.sum()

Numpy

1
2
3
4
5
6
7
8
9
>>> import pandas as pd
>>> import numpy as np
>>> from pandas import Series,DataFrame
>>> arr=np.arange(12).reshape(3,4)
>>> arr
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>>

创建

1
2
3
4
5
6
7
import numpy as np

data1=np.random.randint(1,10,size=5)

>>> data1=np.random.randint(1,10,size=5)
>>> data1
array([1, 9, 7, 7, 2], dtype=int32)

与series的区别

1
2
3
4
5
可以发现Series数组是默认自带索引的,numpy数组也有索引,然而,这两者在索引的使用和性质上存在一些关键的区别

在numpy中,一维数组的索引主要是基于位置的,从0开始并且与数据的位置有关。这种索引主要用来访问数组中的元素,但它并不提供额外的元数据或分类功能。换句话说,numpy数组的索引主要是为了定位元素,而不是为了数据的分类或标签。

相比之下,pandas的Series数组具有更复杂的索引结构。除了基于位置的索引外,Series还可以附加额外的索引,这些索引通常是字符串或其他对象类型,用于分类或标记数据。这些额外的索引使得Series数组能够更好地处理复杂的数据集,其中的数据可能需要根据多个维度或标准进行分类或查询。

.concatenate()

1
2
用于将多个numpy数组进行串接
axis=1相当于增加列,axis=0相当于增加行
1
2
3
4
5
6
7
8
9
10
11
>>> np.concatenate([arr,arr],axis=1)
array([[ 0, 1, 2, 3, 0, 1, 2, 3],
[ 4, 5, 6, 7, 4, 5, 6, 7],
[ 8, 9, 10, 11, 8, 9, 10, 11]])
>>> np.concatenate([arr,arr],axis=0)
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])