如何在Python中从CSV导入数组数组

如何在Python中从CSV导入数组数组,python,arrays,python-3.x,csv,numpy,Python,Arrays,Python 3.x,Csv,Numpy,所以基本上我是Python新手,有些事情我做不到。我正在从CSV导入数据,我需要我的数据\u 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]] Time_Activity;SITTING;

所以基本上我是Python新手,有些事情我做不到。我正在从CSV导入数据,我需要我的数据\u 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]]
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
相反,使用我当前的代码,我得到了以下结果:

[['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文件当前如下所示:

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]]
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

要立即修复,请使用该方法将字符串数组转换为
int

data_array = data_array.astype(int)
此外,
np.delete
效率低下,不推荐使用;尽可能使用切片。以下是几种完全避免Python级循环的方法:-

numpy
使用NumPy,您可以利用:

pandas
或者,通过熊猫,您可以使用:


csv文件将作为字符串读取。可以在追加时将行从字符串转换为int。这可以使用
map
功能完成

代码:

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

你在正确的轨道上。有两件事可以帮助您实现目标,并稍微简化代码

  • 跳过标题,这样以后就不用担心删除它了
  • 在追加之前将字符串强制转换为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]]
    
    解释这两个添加内容的一些有用链接: