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
    
  • 相关阅读:
    promise.all 发送多个请求
    解决分享里有中文,访问不了的问题
    elementui ztree 编辑的时候,回显半选状态的选项,用isLeaf判断
    倒叙数组查找数组对象中是否有该id值,将其去掉
    https强转
    Decorator学习(一)----- 基础知识
    MySQL的权限系统
    vue-cli 3.0.1 详细入门教程
    vue-cli4.5创建vue项目
    [记录] JavaScript 中的事件(Event对象、事件源对象、事件流、事件绑定)【转发】
  • 原文地址:https://www.cnblogs.com/TTyb/p/9717519.html
Copyright © 2011-2022 走看看