numpy创建二维数组报错:Field elements must be 2- or 3-tuples,got '6'
解决numpy创建二维数组时的TypeError报错
错误原因
你写的np.array([1,2,3,4,5],[6,7,8,9,10])不符合numpy数组的创建规则。np.array()的第一个参数需要是整个数组的元素容器,二维数组要求把每一行的列表嵌套进一个大列表里。你现在把两个列表作为独立参数传给np.array(),第二个列表[6,7,8,9,10]会被当成dtype相关参数处理,numpy解析时出现类型不匹配错误,根本不是什么“六维数组”的问题,纯粹是参数传递逻辑错了。
修正后的代码
import numpy as np # 将两行列表嵌套进一个大列表,作为np.array的唯一位置参数 td = np.array([[1,2,3,4,5],[6,7,8,9,10]]) flattened = td.reshape([1, 10]) # 也可以用更简洁的写法:td.reshape(-1),让numpy自动计算维度 # flattened = td.reshape(-1) print(flattened)
运行后会输出:
[[ 1 2 3 4 5 6 7 8 9 10]]
内容的提问来源于stack exchange,提问作者pearlwrap
相关产品推荐
相关产品推荐

