zoukankan      html  css  js  c++  java
  • numpy操作

    python中使用了numpy的一些操作,特此记录下来:

    生成矩阵,替换值

    import numpy as np
    # 生成一行10列的矩阵
    dataset = np.zeros((1, 10))
    # 将位置为2的值替换为1
    dataset.itemset(2, 1)
    

    得到结果为:

    [[0. 0. 1. 0. 0. 0. 0. 0. 0. 0.]]
    

    where查找

    import numpy as np
    dataset = np.array([1, 2, 3, 2, 3, 4, 4, 5, 6])
    # 找到值等于2的值的下标
    dataset = np.where(dataset == 2)
    print(dataset)
    
    dataset = np.array([1, 2, 3, 2, 3, 4, 4, 5, 6])
    index = np.argwhere(dataset == 2)
    print(index)
    

    得到结果为:

    (array([1, 3], dtype=int64),)
    
    [[1]
     [3]]
    

    增加一行或一列

    import numpy as np
    dataset = np.array([[1, 2, 3], [2, 3, 4], [4, 5, 6]])
    # 增加行
    a = np.row_stack((dataset, [8,9,10]))
    print(a)
    
    # 增加列
    b = np.column_stack((dataset, [8,9,10]))
    print(b)
    

    得到结果为:

    [[ 1  2  3]
     [ 2  3  4]
     [ 4  5  6]
     [ 8  9 10]]
     
    [[ 1  2  3  8]
     [ 2  3  4  9]
     [ 4  5  6 10]]
    

    按行合并,按列合并

    import numpy as np
    dataset = np.array([[1, 2, 3], [2, 3, 4], [4, 5, 6]])
    # 按行合并
    dataset = np.append(dataset, [[8, 9, 10]], axis=0)
    print(dataset)
    
    dataset = np.array([[1, 2, 3], [2, 3, 4], [4, 5, 6]])
    # 按列合并
    dataset = np.append(dataset, [[8], [9], [10]], axis=1)
    print(dataset)
    

    得到结果为:

    [[ 1  2  3]
     [ 2  3  4]
     [ 4  5  6]
     [ 8  9 10]]
     
    [[ 1  2  3  8]
     [ 2  3  4  9]
     [ 4  5  6 10]]
    

    删除行、列

    import numpy as np
    dataset = np.array([[1, 2, 3], [2, 3, 4], [4, 5, 6]])
    # 删除第1、2行(0、1、2)
    dataset = np.delete(dataset, [1, 2], axis=0)
    print(dataset)
    
    dataset = np.array([[1, 2, 3], [2, 3, 4], [4, 5, 6]])
    # 删除第1、2列(0、1、2)
    dataset = np.delete(dataset, [1, 2], axis=1)
    print(dataset)
    

    得到结果为:

    [[1 2 3]]
    
    [[1]
     [2]
     [4]]
    

    ndarray转dataframe

    import numpy as np
    import pandas as pd
    
    dataset = np.array([[1, 2, 3], [2, 3, 4], [4, 5, 6]])
    dataframe = pd.DataFrame(dataset, index=("row1", "row2", "row3"), columns=("col1", "col2", "col3"))
    print(dataframe)
    

    得到结果为:

          col1  col2  col3
    row1     1     2     3
    row2     2     3     4
    row3     4     5     6
    
  • 相关阅读:
    Linux Kernel 'b43'无线驱动本地特权提升漏洞
    Linux Kernel “dispatch_discard_io()”RO Disk Manipulation安全绕过漏洞
    Linux kernel ‘fill_event_metadata’函数资源管理错误漏洞
    Linux kernel ‘b43_request_firmware’函数格式化字符串漏洞
    phpcms 2007 onunload.inc.php update SQL注入漏洞
    出差到天津的计划
    Auguries of Innocence
    做一个东西要多久
    Wise Installation 9 的一个容易忽视的选项
    天津行总结路在嘴底下
  • 原文地址:https://www.cnblogs.com/TTyb/p/9717519.html
Copyright © 2011-2022 走看看