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
    
  • 相关阅读:
    Vue- 对象语法 v-bind:class与对象语法的使用(重要)
    关于vue中$emit事件问题
    深入理解vue.js2.0指令v-for使用及索引获取
    到底vuex是什么?
    Vue.js学习系列二 —— vuex学习实践笔记(附DEMO)
    前端HTML5几种存储方式的总结
    JSON和JS对象之间的互转
    Vue2.0子父组件通信
    C#字符串和16进制转换
    C#中int32 的有效值范围
  • 原文地址:https://www.cnblogs.com/TTyb/p/9717519.html
Copyright © 2011-2022 走看看