【问题标题】:Store csv file in array removing first column [Python]将 csv 文件存储在数组中删除第一列 [Python]
【发布时间】:2016-12-15 12:28:14
【问题描述】:

我想将 csv 文件存储在 python 中的数组中,删除第一列。为了存储它,我只写了这两行代码

from numpy import genfromtxt
def csvToArray():
    data = genfromtxt('SP500Index.csv', delimiter=',')
    return array

它奏效了。从这一点来说,我怎样才能摆脱第一列?

【问题讨论】:

  • 如果你恰好知道你正在处理的列数(num_cols),那么你可以通过genfromtext方法直接得到你想要的列:data = genfromtxt('SP500Index.csv', delimiter=',', usecols = range(1,num_cols))。跨度>
  • 谢谢!我不知道 usecols 参数。

标签: python arrays csv numpy


【解决方案1】:

只需使用 numpy.delete 函数。在代码中添加如下:

import numpy as np

def csvToArray():
    data = np.genfromtxt('SP500Index.csv', delimiter=',')
    data = np.delete(data, 0, 1) # the first input is the array, second is
                          #   which row/column to delete, third
                          #   determines if it is row (0) or column (1)
    return data #not sure why it had array before

Numpy 的 delete 文档是 here

【讨论】:

    猜你喜欢
    • 2020-05-15
    • 2021-09-15
    • 2019-07-02
    • 1970-01-01
    • 2013-06-05
    • 2016-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多