无法将数组转换为浮点数python

Ash*_*ton 5 python csv arrays floating-point numpy

我遇到的问题似乎很容易解释答案.我正在努力将我的数组元素转换为浮点数(这样我可以繁殖,添加它们等)

import csv
import os
import glob
import numpy as np

def get_data(filename):
    with open(filename, 'r') as f:
        reader = csv.reader(f)                      
        return list(reader)

all_data = []

path=raw_input('What is the directory?')       
for infile in glob.glob(os.path.join(path, '*.csv')):
     all_data.extend(get_data(infile))
a = np.array(all_data)
current_track_data=a[0:,[8,9,10,11,12]]
abs_track_data=a[0:,7]
Run Code Online (Sandbox Code Playgroud)

我收到错误:

> --------------------------------------------------------------------------- ValueError                                Traceback (most recent call last) C:\Users\AClayton\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.0.3.1262.win-x86_64\lib\site-packages\IPython\utils\py3compat.pyc in execfile(fname, glob, loc)
    174             else:
    175                 filename = fname
--> 176             exec compile(scripttext, filename, 'exec') in glob, loc
    177     else:
    178         def execfile(fname, *where):
> 
> C:\Users\AClayton\Current\python begin\code_tester2.py in <module>()
>      18 for infile in glob.glob(os.path.join(path, '*.csv')): # performs loop for each file in the specified path with extension .csv
>      19      all_data.extend(get_data(infile))
> ---> 20      a = np.ndarray(all_data, dtype=float)
>      21 
>      22      current_track_data=a[0:,[8,9,10,11,12]]
> 
> ValueError: sequence too large; must be smaller than 32
Run Code Online (Sandbox Code Playgroud)

Jai*_*ime 12

您的脚本与您发布的代码不同...由于您的错误的回溯显示,在第20行您正在调用np.ndarray.这是numpy数组对象,而不是np.array 工厂函数.除非您非常清楚自己在做什么,否则请遵循文档建议并:

阵列应该使用来构造array,zeros或empty(参见同样,见部分下方).这里给出的参数是指ndarray(...)用于实例化数组的低级方法().

所以将您的第20行更改为:

 a = np.array(all_data, dtype=float)
Run Code Online (Sandbox Code Playgroud)

你应该没事

您得到的错误是因为ndarray您将第一个输入作为要创建的数组的形状.在我的Windows系统上设置为32的维度数量有一个受限制的限制(可能与平台有关,不确定).您的all_data列表包含超过32个条目(或您系统中的任何值),被误解为维度的大小,这就是触发错误的原因.