【问题标题】:too many indices for array while splitting array拆分数组时数组的索引过多
【发布时间】:2021-01-19 22:27:46
【问题描述】:

我正在尝试读取 csv 文件并将数据存储到二维数组中。但是,在将数据放入二维数组之前,我想获取位于 csv 顶部的标题数据并将其存储在自己的数组中。

import csv
import numpy as np

with open ('parkinsons.data.csv','r') as csv_file:
    row_count = sum(1 for row in csv_file)  # fileObject is your csv.reader





readArray = np.zeros(shape=(row_count,24));
print(readArray)

with open ('parkinsons.data.csv','r') as csv_file:
    lineCount = 0;
    for line in csv_file:
        if(lineCount == 0):
            temp = np.char.split(line, sep=',')
            lineCount = lineCount + 1;
            print(temp) ##When I print this out I can see the entire array
            print(temp[0])## When I try to print this out i get an error




csv_file.close()

这是我尝试从数组中打印出特定位置时遇到的错误(例如 temp[0]

但是,如果我只是打印 temp,那么它会显示所有数据。如果我尝试使用 np.shape,它会说数组是空的。

我对 python 和 numpy 有点陌生,所以欢迎任何帮助,我看到一些人遇到了同样的问题,但我明白他们为什么会遇到这些问题,我不明白我为什么会得到它。谢谢。

【问题讨论】:

  • 你为什么使用np.char.split而不是基本的python字符串分割? list.split(',')?

标签: python numpy csv


【解决方案1】:

首先回答您的问题,您存储temp 的数据结构是一个数组,其唯一成员是一个列表。如果你要这样做,

np.size(temp)

输出将是()。如果你真的想要,你可以通过以下方式访问temp 的内容:

print(temp[()])

但这(强烈)不推荐。这是一个更好的方法:

import csv
import numpy as np

with open('temp.csv') as csvfile:
    csv_reader = csv.reader(csvfile)
    
    for row in csv_reader:
        if (csv_reader.line_num == 1):
            header = row

我使用的示例 csv 文件 (temp.csv) 在哪里,

head, shoulders, knees, toes
1, 2, 3, 4
4, 3, 2, 1

这里,header 应该是您请求的标头数据数组。

PS:因为我喜欢这个包,所以我可能有点受贿,但使用pandas 更容易实现:

import pandas as pd

csv_file = pd.read_csv('temp.csv')
header = csv_file.columns

这会给你同样的结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-22
    • 2019-10-07
    • 2018-01-08
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多