• numpy&pandas笔记


    1.基础属性:

    1 array = np.array([[1,2,3],[2,3,4]])  #列表转化为矩阵
    2 print('number of dim:',array.ndim)  # 维度
    3 # number of dim: 2
    4 
    5 print('shape :',array.shape)    # 行数和列数
    6 # shape : (2, 3)
    7 
    8 print('size:',array.size)   # 元素个数
    9 # size: 6

    创建array:注意其形式为([,,,])      ,若为矩阵其形式为([[,,,],[,,,]])

    a = np.array([2,23,4])  # list 1d

    a = np.array([2,23,4],dtype=np.float)       #指定数据类型

    a = np.zeros((3,4)) # 数据全为0,3行4列

    a = np.arange(10,20,2)                          # 10-19 的数据,2步长,常用创建区间数组

    a = np.arange(12).reshape((3,4))    # 3行4列,0到11      #改变形状

    2.基础计算:

    在Numpy中,想要求出矩阵中各个元素的乘方需要依赖双星符号 **,以二次方举例,即:

    c = a**2 

    矩阵乘法:

    c = a.dot(b)

    对矩阵中的元素操作:
    np.sum(a)   
    np.min(a)  
    np.max(a

    其中的 argmin()argmax() 两个函数分别对应着求矩阵中最小元素和最大元素的索引

    print(np.mean(A))  均值

    A.T即为转置矩阵

    A = np.arange(3,15).reshape((3,4))        #将一个一维的数据转换为矩阵

    A.flatten()                                           #将一个多维平铺成一维数组

    for item in A.flat:

      print(item)              #flat为一个迭代器对象

    3.numpy合并与分割:

    np.vstack((A,B))上下合并

    np.hstack((A,B))左右合并

    把一些序列并不表示矩阵的转换为矩阵:

    1 print(A[np.newaxis,:])
    2 # [[1 1 1]]
    3 
    4 print(A[np.newaxis,:].shape)
    5 # (1,3)
    6 
    7 
    8 print(A[:,np.newaxis].shape)
    9 # (3,1)

     对于多个序列的合并采用另外一个函数:

     1 C = np.concatenate((A,B,B,A),axis=0)
     2 
     3 print(C)
     4 """
     5 array([[1],
     6        [1],
     7        [1],
     8        [2],
     9        [2],
    10        [2],
    11        [2],
    12        [2],
    13        [2],
    14        [1],
    15        [1],
    16        [1]])
    17 """
    18 
    19 D = np.concatenate((A,B,B,A),axis=1)
    20 
    21 print(D)
    22 """
    23 array([[1, 2, 2, 1],
    24        [1, 2, 2, 1],
    25        [1, 2, 2, 1]])
    26 """

    axis参数控制单列(0)或者单行(1),0是竖向,1是横向

    vertical垂直的

    numpy的分割具体使用参考莫烦python教程:

    https://morvanzhou.github.io/tutorials/data-manipulation/np-pd/2-7-np-split/

     添加:

    在数据归一化的时候使用Numpy对数据的形状进行调整。

    把一维的列表或者数组调整成多维一个值的矩阵,先使用np.array转换成numpy数组,再使用shuzu.reshape(94,1)

    pandas

    1.Series是一个带索引的序列

    2.DataFrame是一个表格型的数据结构,它包含有一组有序的列,每列可以是不同的值类型(数值,字符串,布尔值等)。

    DataFrame既有行索引也有列索引, 它可以被看做由Series组成的大字典。取某一列元素可以直接用df[列名],返回的值是一个Series。

     1 dates = pd.date_range('20160101',periods=6)
     2 df = pd.DataFrame(np.random.randn(6,4),index=dates,columns=['a','b','c','d'])
     3 
     4 print(df)
     5 """
     6                    a         b         c         d
     7 2016-01-01 -0.253065 -2.071051 -0.640515  0.613663
     8 2016-01-02 -1.147178  1.532470  0.989255 -0.499761
     9 
    10 """

    print(df2.columns)           #每种数据的名称

    print(df2.sort_values(by='B'))      #对数值进行排序

    3.通过标签来筛选数据

     1 print(df.loc['20130102'])
     2 """
     3 A    4
     4 B    5
     5 C    6
     6 D    7
     7 Name: 2013-01-02 00:00:00, dtype: int64
     8 """
     9 
    10 print(df.loc[:,['A','B']]) 
    11 """
    12              A   B
    13 2013-01-01   0   1
    14 2013-01-02   4   5
    15 2013-01-03   8   9
    16 2013-01-04  12  13
    17 2013-01-05  16  17
    18 2013-01-06  20  21
    19 """
    20 
    21 print(df.loc['20130102',['A','B']])
    22 """
    23 A    4
    24 B    5
    25 Name: 2013-01-02 00:00:00, dtype: int64
    26 """

    使用标签来选择数据 loc,选择几列或者几行

    使用ix来混合列组合

    1 print(df.ix[:3,['A','C']])
    2 """
    3             A   C
    4 2013-01-01  0   2
    5 2013-01-02  4   6
    6 2013-01-03  8  10
    7 """

    print(df[df.A>8])            # 还可以使用判断条件来进行筛选。

    4.修改数据

    我们可以利用索引或者标签确定需要修改值的位置

    根据条件设置:df.B[df.A>4] = 0

    添加数据:

    df['E'] = pd.Series([1,2,3,4,5,6], index=pd.date_range('20130101',periods=6))       #长度必须对齐

    5.数据清理

    删除值为nan的数据

    1 df.dropna(
    2     axis=0,     # 0: 对行进行操作; 1: 对列进行操作
    3     how='any'   # 'any': 只要存在 NaN 就 drop 掉; 'all': 必须全部是 NaN 才 drop 
    4     ) 

    如果是将 NaN 的值用其他值代替, 比如代替成 0:

    df.fillna(value=0)

    判断是否有缺失数据 NaN, 为 True 表示缺失数据:

    1 df.isnull() 
    2 """
    3                 A      B      C      D
    4 2013-01-01  False   True  False  False
    5 2013-01-02  False  False   True  False

    检测数据中是否有缺失值:

    np.any(df.isnull()) == True 
    # True

    6.pandas读入与保存,两种简单例子如下

    read读入          data = pd.read_csv('student.csv'),读入进来就是dataframe格式,自动添加行号

    to 保存     data.to_pickle('student.pickle')

     7.pandas的合并

    concat合并方式:

    0是纵向,1是横向

    res = pd.concat([df1, df2, df3], axis=0, ignore_index=True)      重置index

    append合并方式:只有纵向合并

    res = df1.append(df2, ignore_index=True)

    res = df1.append([df2, df3], ignore_index=True)    #合并多个,且都是忽略索引值

     join定义列名的合并方式:具体见代码

     1 #定义资料集
     2 df1 = pd.DataFrame(np.ones((3,4))*0, columns=['a','b','c','d'], index=[1,2,3])
     3 df2 = pd.DataFrame(np.ones((3,4))*1, columns=['b','c','d','e'], index=[2,3,4])
     4 
     5 #纵向"外"合并df1与df2
     6 res = pd.concat([df1, df2], axis=0, join='outer')
     7 
     8 print(res)
     9 #     a    b    c    d    e
    10 # 1  0.0  0.0  0.0  0.0  NaN
    11 # 2  0.0  0.0  0.0  0.0  NaN
    12 # 3  0.0  0.0  0.0  0.0  NaN
    13 # 2  NaN  1.0  1.0  1.0  1.0
    14 # 3  NaN  1.0  1.0  1.0  1.0
    15 # 4  NaN  1.0  1.0  1.0  1.0
    16 
    17 ########下面这个只有相同列名的保存,其他的抛弃
    18 res = pd.concat([df1, df2], axis=0, join='inner')
    19 
    20 #打印结果
    21 print(res)
    22 #     b    c    d
    23 # 1  0.0  0.0  0.0
    24 # 2  0.0  0.0  0.0
    25 # 3  0.0  0.0  0.0
    26 # 2  1.0  1.0  1.0
    27 # 3  1.0  1.0  1.0
    28 # 4  1.0  1.0  1.0

     8,pandas画图函数

    plt.plot()折线图

    plt.scatter()散点图

    具体形式实际应用查询,不需详细记忆。

    
    
  • 相关阅读:
    Python-pymysql
    MySQL学习(3)
    MySQL学习(1)
    MySQL与PostgreSQL哪个更好?
    svn与git区别
    journalctl常用命令
    Spring Cloud 生产环境性能优化
    springcloud优雅停止上下线与熔断
    istio基础详解
    微服务的全链路监控
  • 原文地址:https://www.cnblogs.com/ywheunji/p/10103065.html
Copyright © 2020-2023  润新知