如何在Python导入一个数组的数组从CSV

问题描述 投票:3回答:3

所以基本上我是新来的Python和里面的东西我不能够做。我从CSV导入数据,我需要我的data_2d看起来像这样:

data_2d = [ [30, 15, 0, 15, 0, 0, 0],
        [32, 10, 0,10, 3, 5, 0],
        [5, 9, 0, 25, 10, 8, 3],
        [22, 10, 0  ,17, 5, 6, 0],
        [7, 15, 0, 30, 3, 5, 0]]

取而代之的是,我目前的代码,我得到这样的:

[['30' '15' '0' '15' '0' '0' '0']
['32' '10' '0' '10' '3' '5' '0']
['5' '9' '0' '25' '10' '8' '3']
['22' '10' '0' '17' '5' '6' '0']
['7' '15' '0' '30' '3' '5' '0']]

我的代码是在这里:

data_2d = [ [30, 15, 0, 15, 0, 0, 0],
        [32, 10, 0,10, 3, 5, 0],
        [5, 9, 0, 25, 10, 8, 3],
        [22, 10, 0  ,17, 5, 6, 0],
        [7, 15, 0, 30, 3, 5, 0]]

data_2d = []

with open('file.csv', newline='\n') as f:
    reader = csv.reader(f, delimiter=';')
    for row in reader:
        data_2d.append(row)

data_array = np.array(data_2d)
data_array = np.delete(data_array, (0), axis=0)
data_array = np.delete(data_array, (0), axis=1)

print("data_array")
print(data_array)

CSV文件目前看起来是这样的:

Time_Activity;SITTING;STANDING;LAYING;WALKING;WALKING_DOWNSTAIRS;WALKING_UPSTAIRS;RUNNING
8;30;15;0;15;0;0;0
9;32;10;0;10;3;5;0
10;5;9;0;25;10;8;3
11;22;10;0;17;5;6;0
12;7;15;0;30;3;5;0
python arrays python-3.x csv numpy
3个回答
1
投票

对于立即修复,使用astype方法的字符串数组转换为int

data_array = data_array.astype(int)

此外,np.delete是低效和不推荐;改用切片在可能的情况。这里有几个方法可以避开的Python级循环干脆: -

numpy

使用NumPy的,你可以利用np.genfromtxt

arr = np.genfromtxt('file.csv', delimiter=';', skip_header=1)[:, 1:]

pandas

另外,通过大熊猫可以使用pd.read_csv

arr = pd.read_csv('file.csv', sep=';').iloc[:, 1:].values

print(arr)

# array([[30, 15,  0, 15,  0,  0,  0],
#        [32, 10,  0, 10,  3,  5,  0],
#        [ 5,  9,  0, 25, 10,  8,  3],
#        [22, 10,  0, 17,  5,  6,  0],
#        [ 7, 15,  0, 30,  3,  5,  0]], dtype=int64)

3
投票

CSV文件读取为字符串。您可以行从字符串转换,同时追加为int。这可以通过使用map函数来完成。

码:

data_2d.append(list(map(int,row)))

1
投票

你是在正确的轨道上。两件事情可以帮助实现自己的目标,并简化代码位。

  1. 跳过头,所以你不用担心以后将其删除。
  2. 铸造字符串你之前追加为int。

示例代码,您输入的工作原理:

  data_2d = []
  with open('file.csv', newline='\n') as f:
    reader = csv.reader(f, delimiter=';')
    next(reader) # this will skip that header
    for row in reader:
      data_2d.append([int(x) for x in row]) #this just means take each string and make it an int before appending.

结果:

[[8, 30, 15, 0, 15, 0, 0, 0], 
[9, 32, 10, 0, 10, 3, 5, 0], 
[10, 5, 9, 0, 25, 10, 8, 3], 
[11, 22, 10, 0, 17, 5, 6, 0], 
[12, 7, 15, 0, 30, 3, 5, 0]]

解释两次加入一些有用的链接:https://evanhahn.com/python-skip-header-csv-reader/ https://www.pythonforbeginners.com/basics/list-comprehensions-in-python

© www.soinside.com 2019 - 2024. All rights reserved.