【发布时间】:2016-11-15 02:12:38
【问题描述】:
这是我第一次使用 python,我正在制作一个父亲和孩子的数组,我有一个 .csv 文件中的数据集,我需要进入 python,以便以后可以将其转移到 java 脚本中。然而,同样的错误信息不断出现,我在下面放了。再往下是我的剧本。非常感谢您的任何建议!
加布里埃拉
>>> runfile('/Users/gkountourides/Desktop/FunctionalExperiment/untitled0.py', wdir='/Users/gkountourides/Desktop/FunctionalExperiment')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "//anaconda/lib/python3.5/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 714, in runfile
execfile(filename, namespace)
File "//anaconda/lib/python3.5/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 89, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "/Users/gkountourides/Desktop/FunctionalExperiment/untitled0.py", line 41, in <module>
father,child = fc_csv_to_javascript_arrays("/Users/gkountourides/Desktop/FunctionalExperiment/fatherChild.csv")
File "/Users/gkountourides/Desktop/FunctionalExperiment/untitled0.py", line 38, in fc_csv_to_javascript_arrays
father_str, child_str = from_fc_array_to_fc_string(full_array)
File "/Users/gkountourides/Desktop/FunctionalExperiment/untitled0.py", line 30, in from_fc_array_to_fc_string
father_array = input_2d_array[:,0]
IndexError: too many indices for array
>>>
然后是我的实际脚本:
import glob
import numpy as np
def list_all_jpgs():
javascript_string = "["
for filename in glob.glob("*.jpg"):
javascript_string += '"' + filename + '",'
javascript_string = javascript_string[0:-1] + "]"
return javascript_string
def load_into_np_array(input_csv_file):
loaded_array = np.genfromtxt(input_csv_file, dtype=str, delimiter=",")
return loaded_array
def from_single_array_to_string(input_1d_array):
output_string = '['
for entry in input_1d_array:
output_string += '"'+str(entry)+'",'
output_string = output_string[0:-1]+']'
return output_string
def from_fc_array_to_fc_string(input_2d_array):
father_array = input_2d_array[:,0]
child_array = input_2d_array[:,1]
father_string = from_single_array_to_string(father_array)
child_string = from_single_array_to_string(child_array)
return father_string, child_string
def fc_csv_to_javascript_arrays(csv_input):
full_array = load_into_np_array(csv_input)
father_str, child_str = from_fc_array_to_fc_string(full_array)
return father_str, child_str
father,child = fc_csv_to_javascript_arrays("/Users/gkountourides/Desktop/FunctionalExperiment/fatherChild.csv")
print(father)
print(child)
【问题讨论】:
-
您尝试过什么调试?我从错误中猜测变量
input_2d_array实际上不是 2d,尝试将其打印出来并打印出它的.shape。 -
嗨,“打印出来”是什么意思?对不起,我是新手,更多细节会很有帮助。谢谢!
-
想通了——我用的是mac,我需要将它保存为windows csv,而不是默认的mac!
-
“默认mac one”是什么意思?文件扩展名
.csv用于标准文本文件,并且跨所有操作系统交叉兼容。打印出来意味着使用printfunction for python3 或[printpython2 的语句]()。无论哪种方式,在失败的行上方添加print(input_2d_array) ; print(input_2d_array.shape)都会在失败之前将数据显示到控制台。
标签: python arrays numpy error-handling