代码学习

作者: 安于此生__ | 来源:发表于2018-04-12 10:16 被阅读0次

    通过reset_index()函数可以将groupby()的分组结果转换成DataFrame对象

    pop() 函数用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。

    获取DataFrame的列名是一个比较简单的操作,又以下几个方法:

    • [column for column in df]
    • df.columns.values 返回 array, 可以通过 tolist(), 或者 list(array) 转换为list,一般 tolist()效率更高。
    • list(df)
    • df.columns 返回Index,可以通过 tolist(), 或者 list(array) 转换为list

    enumerate()说明

    • enumerate()是python的内置函数
    • enumerate在字典上是枚举、列举的意思
    • 对于一个可迭代的(iterable)/可遍历的对象(如列表、字符串),enumerate将其组成一个索引序列,利用它可以同时获得索引和值
    • enumerate多用于在for循环中得到计数
    • enumerate()返回的是一个enumerate对象,例如:
    list1 = ["这", "是", "一个", "测试"]
    for index, item in enumerate(list1):
        print index, item
    >>>
    0 这
    1 是
    2 一个
    3 测试
    

    https://blog.csdn.net/kancy110/article/details/75043202
    fit(y) Fit label encoder
    fit_transform(y) Fit label encoder and return encoded labels
    fit 返回一个实例
    fit_transform 返回 和y一样的形状

    from sklearn import preprocessing
    le = preprocessing.LabelEncoder()
    '''fit_transform的用法'''
    city = le.fit_transform(["paris", "paris", "tokyo", "amsterdam"])
    print city
    1
    2
    3
    4
    

    得到一列 [1 1 2 0]

    from sklearn.preprocessing import LabelEncoder,OneHotEncoder
    lb = LabelEncoder()
    enc = OneHotEncoder()
    tmp=lb.fit_transform((list(train[feat])+list(val[feat])+list(test_a[feat])))
    enc.fit(tmp.reshape(-1,1))
    

    https://blog.csdn.net/weixin_39449570/article/details/78619196
    reshape函数参数-1的含义:
    新数组的shape属性应该要与原来数组的一致,即新数组元素数量与原数组元素数量要相等。一个参数为-1时,那么reshape函数会根据另一个参数的维度计算出数组的另外一个shape属性值。

    >>> z = np.array([[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12],[13, 14, 15, 16]])
    
    >>> print(z)
    [[ 1  2  3  4]
     [ 5  6  7  8]
     [ 9 10 11 12]
     [13 14 15 16]]
    >>> print(z.shape)
    (4, 4)
    >>> print(z.reshape(-1))
    [ 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16]
    >>> print(z.reshape(-1,1))  #我们不知道z的shape属性是多少,
                                #但是想让z变成只有一列,行数不知道多少,
                                #通过`z.reshape(-1,1)`,Numpy自动计算出有16行,
                                #新的数组shape属性为(16, 1),与原来的(4, 4)配套。
    [[ 1]
     [ 2]
     [ 3]
     [ 4]
     [ 5]
     [ 6]
     [ 7]
     [ 8]
     [ 9]
     [10]
     [11]
     [12]
     [13]
     [14]
     [15]
     [16]]
    >>> print(z.reshape(2,-1))
    [[ 1  2  3  4  5  6  7  8]
     [ 9 10 11 12 13 14 15 16]]
    

    one-hot编码

    one-hot编码 https://blog.csdn.net/gao1440156051/article/details/55096630

    #-*-coding:utf-8-*-
    import pandas as pd
    import numpy as np
    from sklearn.preprocessing import OneHotEncoder
    from sklearn.preprocessing import LabelEncoder
    from sklearn.preprocessing import LabelBinarizer
    from sklearn.preprocessing import MultiLabelBinarizer
    
    testdata = pd.DataFrame({'pet': ['cat', 'dog', 'dog', 'fish'],'age': [4 , 6, 3, 3],
    'salary':[4, 5, 1, 1]})
    #-*-coding:utf-8-*-
    import pandas as pd
    import numpy as np
    from sklearn.preprocessing import OneHotEncoder
    from sklearn.preprocessing import LabelEncoder
    from sklearn.preprocessing import LabelBinarizer
    from sklearn.preprocessing import MultiLabelBinarizer
    
    testdata = pd.DataFrame({'pet': ['cat', 'dog', 'dog', 'fish'],'age': [4 , 6, 3, 3],'salary':[4, 5, 1, 1]})
    OneHotEncoder(sparse =False).fit_transform(testdata[['age']]) 
    #这里我们把 pet、age、salary 都看做类别特征,所不同的是 age 和 salary 都是数值型,而 pet 是字符串型。我们的目的很简单: 把他们全都二值化,进行 one-hot 编码.
    #sklearn 的新版本中,OneHotEncoder 的输入必须是 2-D array,而 testdata.age 返回的 Series 本质上是 1-D array,所以要改成2-D array"""
    
    out:
    array([[ 0.,  1.,  0.],
         [ 0.,  0.,  1.],
         [ 1.,  0.,  0.],
         [ 1.,  0.,  0.]])
    a1 = OneHotEncoder(sparse = False).fit_transform( testdata[['age']] )
    a2 = OneHotEncoder(sparse = False).fit_transform( testdata[['salary']])
    final_output = np.hstack((a1,a2))
    final_output
    out:
    array([[ 0.,  1.,  0.,  0.,  1.,  0.],
         [ 0.,  0.,  1.,  0.,  0.,  1.],
         [ 1.,  0.,  0.,  1.,  0.,  0.],
         [ 1.,  0.,  0.,  1.,  0.,  0.]])
    等价的写法:
    OneHotEncoder(sparse = False).fit_transform(testdata.age.values.reshape(-1,1))
    """遗憾的是OneHotEncoder无法直接对字符串型的类别变量编码.
    
    方法一 先用 LabelEncoder() 转换成连续的数值型变量,再用 OneHotEncoder() 二值化
    方法二 直接用 LabelBinarizer() 进行二值化 然而要注意的是,无论 LabelEncoder() 还是 LabelBinarizer(),他们在 sklearn 中的设计初衷,都是为了解决标签 y的离散化,
    而非输入X, 所以他们的输入被限定为 1-D array,这恰恰跟OneHotEncoder() 要求输入 2-D array 相左。所以我们使用的时候要格外小心,否则出错."""
    # 方法一: LabelEncoder() + OneHotEncoder()
    a = LabelEncoder().fit_transform(testdata['pet'])
    OneHotEncoder( sparse=False ).fit_transform(a.reshape(-1,1)) # 注意: 这里把 a 用 reshape 转换成 2-D array
    
    # 方法二: 直接用 LabelBinarizer()
    
    LabelBinarizer().fit_transform(testdata['pet'])
    out:
    array([[1, 0, 0],
         [0, 1, 0],
         [0, 1, 0],
         [0, 0, 1]])
    

    sparse.hstack()

    可以使用numpy hstack或者sparse hstack把所有的特征水平堆叠起来,这取决你拥有的是稀疏或者紧密特征。

    >>> from scipy.sparse import coo_matrix, hstack
    >>> A = coo_matrix([[1, 2], [3, 4]])
    >>>print(A)
      (0, 0)    1
      (0, 1)    2
      (1, 0)    3
      (1, 1)    4
    >>> B = coo_matrix([[5], [6]])
    >>> hstack([A,B]).toarray()
    array([[1, 2, 5],
           [3, 4, 6]])
    

    Numpy中stack(),hstack(),vstack()函数详解

    import numpy as np
    a=[[1,2,3],
       [4,5,6]]
    print("列表a如下:")
    print(a)
    out:
    列表a如下:
    [[1, 2, 3], [4, 5, 6]]
    
    print("增加一维,新维度的下标为0")
    c=np.stack(a,axis=0)
    print(c)
    out:
    [[1 2 3]
     [4 5 6]]
    
    print("增加一维,新维度的下标为1")
    c=np.stack(a,axis=1)
    print(c)
    增加一维,新维度的下标为1
    out:
    [[1 4]
     [2 5]
     [3 6]]
    
    import numpy as np
    a=[[1,2,3,4],
       [5,6,7,8],
       [9,10,11,12]]
    print("列表a如下:")
    print(a)
    out:列表a如下:
    [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
    
    print("增加一维,新维度的下标为0")
    c=np.stack(a,axis=0)
    print(c)
    out:增加一维,新维度的下标为0
    [[ 1  2  3  4]
     [ 5  6  7  8]
     [ 9 10 11 12]]
    
    print("增加一维,在axis = 1的方向上")
    c= np.stack(a,axis = 1)
    print(c)
    out:增加一维,在axis = 1的方向上
    [[ 1  5  9]
     [ 2  6 10]
     [ 3  7 11]
     [ 4  8 12]]
    
    a = [1,2,3,4]
    b = [5,6,7,8]
    c =[9,10,11,12]
    a
    out:[1, 2, 3, 4]
    
    d = np.stack((a,b,c),axis = 0)
    print(d)
    out:
    [[ 1  2  3  4]
     [ 5  6  7  8]
     [ 9 10 11 12]]
    
    d = np.stack((a,b,c),axis = 1)
    print(d)
    out:
    [[ 1  5  9]
     [ 2  6 10]
     [ 3  7 11]
     [ 4  8 12]]
    
    a=[[1,2,3],
       [4,5,6]]
    b=[[7,8,9],
       [4,5,6]]
    c=[[11,12,13],
       [14,15,16]]
    
    d = np.stack((a,b,c),axis = 0)
    print(d)
    [[[ 1  2  3]
      [ 4  5  6]]
    
     [[ 7  8  9]
      [ 4  5  6]]
    
     [[11 12 13]
      [14 15 16]]]
    
    
    d = np.stack((a,b,c),axis = 1)
    print(d)
    [[[ 1  2  3]
      [ 7  8  9]
      [11 12 13]]
    
     [[ 4  5  6]
      [ 4  5  6]
      [14 15 16]]]
    
    d = np.stack((a,b,c),axis = 2)
    print(d)
    [[[ 1  7 11]
      [ 2  8 12]
      [ 3  9 13]]
    
     [[ 4  4 14]
      [ 5  5 15]
      [ 6  6 16]]]
    hstack()函数 函数原型:hstack(tup) ,参数tup可以是元组,列表,或者numpy数组,返回结果为numpy的数组。看下面的代码体会它的含义
    
    import numpy as np
    a=[1,2,3]
    b=[4,5,6]
    print(np.hstack((a,b)))
    [1 2 3 4 5 6]
    
    a=[[1],[2],[3]]
    b=[[1],[2],[3]]
    c=[[1],[2],[3]]
    d=[[1],[2],[3]]
    print(np.hstack((a,b,c,d)))
    import numpy as np
    a=[[1],[2],[3]]
    b=[[1],[2],[3]]
    c=[[1],[2],[3]]
    d=[[1],[2],[3]]
    print(np.hstack((a,b,c,d)))
    [[1 1 1 1]
     [2 2 2 2]
     [3 3 3 3]]
    
    import numpy as np
    a=[1,2,3]
    b=[4,5,6]
    print(np.vstack((a,b)))
    [[1 2 3]
     [4 5 6]]
    
    a=[[1],[2],[3]]
    b=[[1],[2],[3]]
    c=[[1],[2],[3]]
    d=[[1],[2],[3]]
    print(np.vstack((a,b,c,d)))
    [[1]
     [2]
     [3]
     [1]
     [2]
     [3]
     [1]
     [2]
     [3]
     [1]
     [2]
     [3]]
    

    np.vstack(([1,2,3],[4,5,6]))
    out:
    array([[1, 2, 3],
    [4, 5, 6]])
    np.column_stack(([1,2,3],[4,5,6]))
    out:
    array([[1, 4],
    [2, 5],
    [3, 6]])
    np.hstack(([1,2,3],[4,5,6]))
    out:
    array([1, 2, 3, 4, 5, 6])

    sparse

    COO使用3个数组进行存储:values,rows, andcolumn。

    其中
    数组values: 实数或复数数据,包括矩阵中的非零元素,顺序任意。
    数组rows: 数据所处的行。
    数组columns: 数据所处的列。
    参数:矩阵中非零元素的数量 nnz,3个数组的长度均为nnz.

    相关文章

      网友评论

        本文标题:代码学习

        本文链接:https://www.haomeiwen.com/subject/obbzhftx.html