2_numpy,pandas,matplotlib

221 阅读3分钟

numpy

  • 数组 ndarry

    1. np.array(), 声明一个ndarray
    2. np.asarray(), 将一个其他类型转为一个ndarray, 返回新对象。 如果已经是ndarray则不返回新对象
    3. np.arange(st, ed, step),和python的range()一样,返回包头不包尾的ndarray, 可以指定步长step
  • 矩阵

    1. np.arange(20).reshape(4, 5)
    2. np.identity(10, dtype=np.float32), 对角矩阵
    3. np.zeros((4, 5))
    4. np.ones((4, 5))
    5. np.ones_like(X)
  • 随机

    1. np.random.choice(a, size=None, replace=True, p=None)
      • a: (只要是ndarray都可以,但必须是一维的)中随机抽取数字,
      • size:并组成指定大小()的数组, size=None返回数值,指定返回数组
      • replace: 是否重复抽样
      • p:概率数组,表示取数组a中每个元素的概率,默认为选取每个元素的概率相同。
    2. np.random.rand(2, 3, 4)
      • 返回位于[0, 1)的数据,参数是维度,
      • 返回min~max的数据为:min + np.random.rand()*(max-min)
      • 指定维度返回数组,没有参数返回数值
    3. np.random.randint(low, high=None, size=None)
      • 返回一个不小于low的int数
    4. np.random.normal(loc=0.0, scale=1.0, size=None)
      • 从一个正态分布(loc=均值, scale=标准差) ,默认是标准正态分布
    5. np.random.randn(2,3,4)
      • 标准正态分布, 参数是维度,
      • np.random.uniformal(low, high, size)
      • 从一个均匀分布[low,high)中随机采样
    6. np.random.shuffle()
      • 在原数组上进行打乱
    7. np.random.permutation()
      • 生成一个新的打乱的数组
  • 索引拷贝

    ndarray的索引是浅拷贝
    y = x[:, 0]
    y[:]=1
    print(x) # x is changed as well
    
    z = x[0,:].copy()
    
  • 矩阵维度改变

    1. x[:, None, :] 增加一个维度
    2. np.expand_dims(matrix, idx) matrix在下标为dix增加一个维度
    3. np.reshape()
    4. np.squeeze() 去除维度为1的维度。 注意没有unsqueeze(),torch里面有unsqueeze()
    5. np.transpose() 没有参数是转置,有参数是交换维度位置
    6. einops
    7. np.einsum() 合并指定的维度,计算规则 ijh, jkh,合并成ijh,k维度累积求和
  • 广播机制

    1. 主要是不同维度的矩阵相乘引发,注意是点乘,即对应位置的元素相乘
    2. 比如 4 X 2 X 1 X 5 和 4 X 1 X 3 X 5 从后往前看,首先都是5,没问题。然后一个是1,一个是3,此时把维度是1的数据复制3份。继续,把维度为1的变为2份,继续都是4没问题。 所以最终就是4 X 2 X 3 X 5
    3. 注意矩阵和向量相乘,也是从后往前看。

pandas

  • concat

    1. axis=0是index合并,把index合并到一起,竖着拼接, 数据的列必须相等
    2. axis=1是columns合并,把columns合并到一起,横着拼接,数据的行必须相等
  • loc和iloc索引

    1. loc是按条件索引 data.loc[data['VehicleAge']>3, 'VehicleAge', 'Other']

    2. iloc是按下标索引 data.iloc[0:100, 0:2]

  • groupby

    df_tmp.groupby('IsBadBuy', as_index=False)['VehicleAge'].mean()  
    # 这里as_index就起作用了,即是否把主键作为index,默认是True
    # 多个聚合操作, 并命名字
    df_tmp.groupby('IsBadBuy', as_index=False)['VehicleAge'].agg({'age_mean': np.mean, 
                                                                  'age_sum': np.sum})  
    # map和apply
    # map是对一个series每一个元素
    # apply是对一个df里每一行元素, axis=1是每一行, axis=0是每一列
    # groupby().apply()是先groupby后, 对每一个聚合的元素进行操作
    
  • join

matplotlib

# 折线图
x_axis = [1, 2, 3, 4]
y_axis = [1, 4, 9, 16]
plt.plot(x_axis,y_axis)
plt.show()

# 点图
plt.scatter(x_axis,y_axis)
plt.show()

# 柱状图
x_axis = ['group_a', 'group_b', 'group_c']
y_axis = [1, 10, 100]

plt.bar(x_axis, y_axis)
plt.show()

# 箱型图
#make there Normalize arrays
datas = [np.random.normal(0,std,100) for std in range(1,4)]
print(len(datas))
plt.boxplot(datas) 
plt.show()

# 图的属性
x_axis = [1, 2, 3, 4]
y_axis = [1, 4, 9, 16]

plt.plot(x_axis,y_axis, "r--", label='my num') # 颜色和形状
plt.xlabel("X_label") # add x axis title
plt.ylabel("Y_lable") # add y axis title
plt.title("line_chart") # add picture title
plt.legend(loc='best')  # 图标
plt.xticks(rotation=90)  # x标签旋转
plt.grid()
plt.show()

# 画多图
t=np.arange(0.0,2.0,0.1)
s=np.sin(t*np.pi)
# draw 2 X 2 subplot, plt.subplot(row,column,row), this is the first chart
plt.subplot(2,2,1)
plt.title('chart 1')
plt.plot(t,s,'b--')

# this is the second chart
plt.subplot(2,2,2) 
plt.title('chart 2')
plt.plot(2*t,s,'r--')

# this is the third chart
plt.subplot(2,2,3)
plt.title('chart 3')
plt.plot(3*t,s,'m--')

# this is the fourth chart
plt.subplot(2,2,4)
plt.title('chart 4')
plt.plot(4*t,s,'k--')

plt.show()