总的来说,我对 numpy 和 python 很陌生。当我尝试 append 值时,即使我已确保两个数组具有相同的维度,我也会收到维度不匹配错误。我的另一个问题是为什么 numpy 在从制表符分隔的文本文件读取数据时创建一维数组。
import numpy as np
names = ["Angle", "RX_Power", "Frequency"]
data = np.array([0,0,0],float) #experimental
data = np.genfromtxt("rx_power_mode 0.txt", dtype=float, delimiter='\t', names = names, usecols=[0,1,2], skip_header=1)
freq_177 = np.zeros(shape=(data.shape))
print(freq_177.shape) #outputs(315,)
for i in range(len(data)):
if data[i][2] == 177:
#np.concatenate(freq_177,data[i]) has same issue
np.append(freq_177,data[i],0)
我得到的输出是
all the input arrays must have same number of dimensions
最佳答案
带注释的代码:
import numpy as np
names = ["Angle", "RX_Power", "Frequency"]
您不需要“初始化”数组 - 除非您要为各个元素分配值。
data = np.array([0,0,0],float) #experimental
此数据
分配完全覆盖前一个。
data = np.genfromtxt("rx_power_mode 0.txt", dtype=float, delimiter='\t', names = names, usecols=[0,1,2], skip_header=1)
此时查看数据
。什么是data.shape
?什么是data.dtype
?打印它,或者至少打印一些元素。对于names
,我猜测这是一个一维数组,具有 3 个字段dtype
。不过,它不是一个二维数组,它可以像这样转换/查看所有 float 。
为什么要创建一个一维零数组?
freq_177 = np.zeros(shape=(data.shape))
print(freq_177.shape) #outputs(315,)
对于像data
这样的结构化数组,索引给定元素的首选方法是按字段名称和行号,例如。数据['频率'][i]`。玩这个。
np.append
与列表追加不同。它返回一个值;它不会就地更改freq_177
。与连接
相同。我建议远离np.append
。很容易以错误的方式和地点使用它。
for i in range(len(data)):
if data[i][2] == 177:
#np.concatenate(freq_177,data[i]) has same issue
np.append(freq_177,data[i],0)
您似乎想要在 freq_177
中收集“频率”字段为 177 的 data
数组的所有项。
I = data['frequency'].astype(int)==177
freq_177 = data[I]
我使用了astype(int)
,因为使用浮点的==
测试是不确定的。它最好与整数一起使用。
I
是一个 bool 掩码,值匹配时为 true; data[I]
则为data
对应的元素。 dtype
将与 data
匹配,即它将有 3 个字段。您无法将其 append 或连接到浮点零数组(您的原始 freq_177
)。
如果您必须迭代和收集值,我建议使用列表追加,例如
alist = []
for row in data:
if int(row['frequency'])==177:
alist.append(row)
freq177 = np.array(alist)
<小时/>
我认为除了在其自己的 doc
页面和文本中之外,对 np.append 的讨论不多。它会定期出现在 SO 问题中。
http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.append.html
Returns: append : ndarray
A copy of arr with values appended to axis. Note that append does not occur in-place: a new array is allocated and filled.
另请参阅解释器 shell 中的 help(np.append)
。
对于genfromtxt
- 它也有文档和很多SO讨论。但要了解它在这种情况下返回的内容,您还需要阅读结构化数组
和复合数据类型
。 (添加链接?)
尝试加载数据:
data = np.genfromtxt("rx_power_mode 0.txt", dtype=float, delimiter='\t', usecols=[0,1,2], skip_header=1)
由于您跳过标题行,并且仅使用带有 float 的列,因此 data
应该是一个包含 3 列的二维数组,(N, 3)
。在这种情况下,您可以使用 data[:,2]
I = int(data[:,2])==177
freq_177 = data[I,:]
freq_177
现在是一个 3 列数组 - 包含 data
行的子集。
关于python - numpy数组维度不匹配错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34346625/