zoukankan      html  css  js  c++  java
  • Python Numpy,Pandas基础笔记

    Numpy

    Numpy是python的一个库。支持维度数组与矩阵计算并提供大量的数学函数库。

     1 arr = np.array([[1.2,1.3,1.4],[1.5,1.6,1.7]])#创建ndarray时候也可以指定dtype
     2 arr.astype(dtype = np.int) #浮点数转int
     3 #对数组批量运算,作用在每个元素上
     4 arr = np.array([[1,2,3],[4,5,6]])
     5 print arr**5
     6 #索引和切片
     7 arr = np.array([1,2,3,4,5,6])
     8 print arr[:2]#arr[0]和arr[1]
     9 arr = np.array([[1,2,3],[4,5,6]])
    10 print arr[:2] #打印第1,2行
    11 
    12 #布尔型索引
    13 name = ['Bob','La','CA','Da','Ea','Fa']
    14 rnd_arr = np.random.randn(7,4)
    15 print rnd_arr[name == 'CA']#利用布尔数组选择行,这里name == 'CA'会产生一个布尔数组
    16 a = [1,2,3]
    17 b = [True,False,True]
    18 print a[b]#选第一个和第三个
    19 
    20 #花式索引
    21 a = [1,2,3,4,5]
    22 index = [4,2,0]
    23 b = a[index]
    24 #对于二维数组 
    25 arr = np.arange(32).reshape(8,4)
    26 print arr[[1,5,2,7],[:,0,3,1,2]] #1,5,2,7行的0,3,2,1列,如果不加冒号就是打印arr[1][0],arr[5][3]   转置 arr.T
    27 #逻辑表述为数组运算where
    28 x = np.random.randn(1,5)
    29 y = np.random.randn(1,5)
    30 cond = np.array([True,False,True,False,True])
    31 result = np.where(cond,x,y)  #也可以省略x,y直接加条件 如 x>2 只有condition的时候返回的是复合条件的坐标索引
    32 #where的逻辑
    33 #如果条件1和2 则0,否则如果条件1取1,否则条件2 取2 ,再不行取3。相当于一个if else的缩写。
    34 #列表推导result = [x if c else y for (c,x,y) in zip(cond,x,y)]
    35 
    36 #数学和统计方法 sum,mean,std,var这些 
    37 arr = np.random.randn(5,4) 
    38 bools = np.array([False,False,True,False]) 
    39 
    40 arr.mean(axis = 1) #按行取平均 
    41 print (arr>0).sum() #大于0的和 
    42 print (bools == True).sum() #True的个数 
    43 print bools.any() #有一个True 都True 
    44 print bools.all() #有一个为False 则False 
    45 unique(x)#去重 ,还有交叉并补 
    46 
    47 
    48 #高斯消元法 qr分解,此外乘法dot,求逆inv 
    49 from numpy.linalg import qr 
    50 arr = np.random.randn(5,4) 
    51 q,r = qr(arr) 
    52 print q,r 
    53 arr.mean(axis = 0) #按照列求均值,也即是竖直方向,如果axis=1则按行求均值,水平方向 
    54 
    55 #数组重塑 
    56 arr = np.arrange(8) 
    57 print arr.reshape(4,2) 
    58 #只是改变了显示方式,其实内存中的存储结构不变 
    59 #下面三种都能达到同样的效果 
    60 x = np.array([[1, 2], [3, 4]]) 
    61 print x.flatten() 
    62 print x.ravel() 
    63 print x.reshape(-1) 
    64 #两者默认均是行序优先 
    65 print x.flatten('F') 
    66 print x.ravel('F') 
    67 print x.T.reshape(-1) 
    68 #flatten ravel的区别 
    69 x = np.array([[1, 2], [3, 4]]) 
    70 x.flatten()[1] = 100 
    71 print x 
    72 # flatten:返回的是拷贝 
    73 x.ravel()[1] = 100 
    74 print x 
    75 #ravel则是对元素组的一个引用,会改变元素组,和reshape一样只是改变了显示方式 
    76 
    77 #连接数组 
    78 a1 = np.array([[0,1,2],[2,1,3]]) 
    79 a2 = np.array([[4,5,6],[7,8,9]]) 
    80 print np.concatenate([a1,a2],axis = 0) #添加行,竖直方向添加,如果axis = 1添加列,水平方向添加 
    81 print np.vstack((a1,a2)) #竖直方向叠起来
    82 print np.hstack((a1,a2)) #水平方向叠起来 和上面的效果一样 
    83 #拆分 
    84 f,s = np.split(a2,[1,2],axis = 0) #竖直方向上,也即是按行拆分 
    85 #put,take 
    86 arr = np.arange(5) 
    87 inds = [1] 
    88 arr.put(inds,50) #替换inds位置的数 
    89 print arr arr.take([1,2]) #和花式索引效果一样

      

    Pandas

    pandas 处理时间序列,缺失数据的处理。

      1 #Series 类似于一维数组,因为平时的数组都是默认索引的,Series可以指定索引。
      2 
      3 from pandas import Series
      4 obj = Series([4,7,-5,3],index = ['a','b','c','d'])
      5 print obj[obj > 0] #找出大于0的
      6 print obj.index
      7 
      8 #字典可以直接生成Series。
      9 locations =['NT','RT','RG','XL']
     10 data = {'NT':4000,'RT':5000,'X':100}
     11 obj = Series(data,index = locations)
     12 print obj
     13 
     14 #Series,相加相同的索引部分相加,也可以给索引以及该series命名。
     15 #index替换
     16 obj.index = [1,2,3,4]
     17 
     18 #DataFrame 可以理解成二元的,他是表格型的数据结构,比如我们平常见的Excel。有行索引,列索引,可以理解成Series的合并。
     19 from pandas import Series,DataFrame
     20 data = {
     21 'locations':['NT','RT','RG','XL'],
     22 'years':[2000,2001,2004,2008],
     23 'pop':[1.5,1.6,1.7,1.8]
     24 }
     25 Df = DataFrame(data, columns = ['years','locations','pop'],index = ['one','two','three','four']) #指定列
     26 print Df
     27 
     28        years locations  pop
     29 one     2000        NT  1.5
     30 two     2001        RT  1.6
     31 three   2004        RG  1.7
     32 four    2008        XL  1.8 
     33 #修改指定的列,可以设置索引,没有的变成NaN。
     34 val = Series([2, 5, 7],index = ['one','two','four'])
     35 Df['pop'] = val
     36 print Df
     37        years locations  pop
     38 one     2000        NT  2.0
     39 two     2001        RT  5.0
     40 three   2004        RG  NaN
     41 four    2008        XL  7.0
     42 Df['big'] = (Df.years == 2008)
     43 
     44 #丢弃指定轴上的项,指定索引或列
     45 print Df.drop(['two','four'],axis = 1)
     46 #索引,选取和过滤
     47 #Series的切片是一个引用
     48 import numpy as np
     49 se = Series(np.arange(4), index = ['a','b','c','d'])
     50 print se['b':'c']
     51 se['b','c'] = 5
     52 print se
     53 
     54 #DataFrame打印列可以直接调用,打印行需要.ix
     55 data = DataFrame(np.arange(16).reshape(4,4),index = ['a','b','c','d'],columns = ['one','two','three','four'])
     56 print data
     57 #print data.ix['a']
     58 print data.ix[:'c','two'] #'two'列的a,b,c行,对于非数字索引一定是闭区间。
     59 data[data < 5] = 0 #所有小于5的都被设置为0
     60 
     61 #算术运算与数字对齐,对齐操作同时发生在行和列上(就是行和列都匹配),索引不对齐的地方计算就是用NA
     62 from pandas import Series
     63 s1 = Series([1,2,3,4,5],index = ['a','b','c','d','e'])
     64 s2 = Series([2,3,4,5,6],index = ['a','b','c','d','f'])
     65 print s1+s2
     66 
     67 a    3.0
     68 b    5.0
     69 c    7.0
     70 d    9.0
     71 e    NaN
     72 f    NaN
     73 dtype: float64
     74 #DataFrame比较复杂,会列出所有的行列,相当于一个并集,然后行列不匹配的那个变成NaN,所有两个DataFrame相加,可能行列大小都会变化,如果不相同的话。
     75 df1 = DataFrame(np.arange(12).reshape(3,4),columns = list('abcd'))
     76 df2 = DataFrame(np.arange(20).reshape(4,5),columns = list('abcde'))
     77 print df1.add(df2,fill_value = 0) #不匹配的,用nan的地方用0填充
     78 
     79       a     b     c     d     e
     80 0   0.0   2.0   4.0   6.0   4.0
     81 1   9.0  11.0  13.0  15.0   9.0
     82 2  18.0  20.0  22.0  24.0  14.0
     83 3  15.0  16.0  17.0  18.0  19.0
     84 #Dataframe和Series之间 相减,默认是按照水平方向,按行,如果axis = 0,则竖直方向,按照列,每一列都减去一个Series。
     85 #函数应用和映射,Series有个应用到元素的map方法,Dataframe有applymap
     86 f = lambda x : x.max() - x.min()
     87 print df1.apply(f, axis = 1)# 对水平方向的每一行最大减最小
     88 print df1.apply(f,axis = 0) # 对竖直方向的每一列最大减最小
     89 
     90 #applymap 应用到每一个元素
     91 df1.astype(np.float)
     92 f2 = lambda x: '%.2f' % x
     93 print df1.applymap(f2)
     94 print df1['a'].map(f2)#df['a']相当于一个Series,应用到每一个元素是map
     95 
     96 #对列和索引进行排序,可以指定升序还是降序还有rank函数
     97 #按照索引排序
     98 df1.sort_index(axis = 1,ascending = False)
     99 
    100      d    c    b    a
    101 0    3    2    1    0
    102 1    7    6    5    4
    103 2    11    10    9    8
    104 
    105 #按值排序
    106 df1.sort_values(by = ['a','b'],ascending = False)#降序,先a按照a,a不行则b
    107 #rank
    108 obj = Series([7,9,-5,1,4,2,2,5])
    109 print obj.rank()#输出的是每个元素应该在的位置
    110 
    111 #指定列变成索引
    112 df1.set_index(['a'])
    113 
    114 #pandas的索引可以用重复,返回的是一个数组
    115 #层次索引
    116 #Series的层次索引
    117 from pandas import Series
    118 s = Series(np.random.randn(5), index = [['a','a','b','b','c'],[1,2,1,2,1]])
    119 print s
    120 print s.index
    121 print s[:2]
    122 print s['b':'c']
    123 print s.unstack() #把1,2放到列上去,c只有1个就变成了NaN了,变成了DataFrame的样子。
    124 print s.unstack().stack()
    125 
    126 a  1   -1.050402
    127    2    0.489801
    128 b  1   -0.538088
    129    2    0.886044
    130 c  1    2.695847
    131 dtype: float64
    132 MultiIndex(levels=[[u'a', u'b', u'c'], [1, 2]],
    133            labels=[[0, 0, 1, 1, 2], [0, 1, 0, 1, 0]])
    134 a  1   -1.050402
    135    2    0.489801
    136 dtype: float64
    137 b  1   -0.538088
    138    2    0.886044
    139 c  1    2.695847
    140 dtype: float64
    141           1         2
    142 a  0.900427 -0.673935
    143 b  0.162862 -0.118564
    144 c  0.039270       NaN
    145 #DataFrame的层次索引,DataFrame不管在行还是列都可以多值索引
    146 df = DataFrame(np.arange(12).reshape((4,3)),index = [['a','a','b','b'],[1,2,1,2]],columns = [['Ohio','Chicago','NewYork'],['a','b','c']])
    147 print df
    148 #交换两个索引,原来在外面的变到里面,也可以根据索引排序
    149 df.index.names = ['key1','key2']
    150 df_df = df.swaplevel('key1','key2')
    151 df_df.swaplevel(0,1).sortlevel(0)
    152 #指定key统计
    153 print df.sum(level = 'key2')
    154      Ohio Chicago NewYork
    155       red    blue   green
    156 key2                     
    157 1       6       8      10
    158 2      12      14      16
    159 #整数索引会有歧义,比如-1,0有时候不知道是位置,还是他的索引,所以避免歧义一般是.iloc
    iloc,loc和ix的区别
    参考自:http://stackoverflow.com/questions/31593201/pandas-iloc-vs-ix-vs-loc-explanation
    s = Series(np.arange(8),index = [8,9,15,1,2,3,4,5])
    print s
    
    8     0
    9     1
    15    2
    1     3
    2     4
    3     5
    4     6          
    5     7
    dtype: int32
    
    print s.iloc[:3]
    8     0
    9     1
    15    2
    dtype: int32
    
    print s.loc[:3]
    8     0
    9     1
    15    2
    1     3
    2     4
    3     5
    dtype: int32
    print s.ix[:,3]
    8     0
    9     1
    15    2
    1     3
    2     4
    3     5
    dtype: int32
    #可以看到.ix和.loc是相同的效果,把3当作是index当中的值,而iloc是打印的前三行。如果是s.ix[:7],s.loc[:7]这样的没有的数,就会报错,而.iloc就会打印前7行。
    #如果是DataFrame,.ix可以索引,位置混合使用,索引选行,列可以取位置切片。
    df = DataFrame(np.arange(12).reshape(3,4),index = list('abc'),columns = ['d','e','f','g'])
    print df
    print df.ix[:'c',:3]
    
      d  e   f   g
    a  0  1   2   3
    b  4  5   6   7
    c  8  9  10  11
       d  e   f
    a  0  1   2
    b  4  5   6
    c  8  9  10
    

     上面numpy,pandas有很多东西没说,还是要实战才容易记住,多多加油吧!

    
    
    
  • 相关阅读:
    opencv 图片像素x,y 访问!!!
    python numpy 三维数组 排序问题
    python+opencv水表识别
    tesseractOCR安装
    cookie 的寻找和使用以及页面滚动(python+selenium)
    你还在用a标签吗?——用button替代a
    js正则高级函数(replace,matchAll用法),实现正则替换(实测很有效)
    腾讯云服务器centos7.2+nginx(开启gzip压缩)+uwsgi+Django+react
    轮播图采用js、jquery实现无缝滚动和非无缝滚动的四种案例实现,兼容ie低版本浏览器
    webstorm 添加css前缀(兼容)自动添加
  • 原文地址:https://www.cnblogs.com/zephyr-1/p/5844201.html
Copyright © 2011-2022 走看看