【发布时间】:2019-07-26 16:35:58
【问题描述】:
我有一个 2D numpy 数组,我希望用索引列表的数字替换它的内容。
这里有一个代码sn-p来描述更清楚:
import numpy as np
x = np.array([
[2, 'something'],
[2, 'more'],
[6, 'and more'],
[11, 'and so on'],
[11, 'etc..']
])
y = [1, 2, 3]
我尝试通过以下代码执行此操作,但出现错误,无法弄清楚为什么会发生。
k = x[:, 0]
z = [2, 6, 11]
j = 0
for i in range(z[0], z[-1] + 1):
k = np.where(i in k, y[j])
j+=1
运行上述代码时出错:
Traceback (most recent call last):
File "<ipython-input-10-c48814c42718>", line 4, in <module>
k = np.where(i in k, y[j])
ValueError: either both or neither of x and y should be given
我想要的输出数组:
# The output array which I intend to get
output = [
[1, 'something'],
[1, 'more'],
[2, 'and more'],
[3, 'and so on'],
[3, 'etc..']
]
【问题讨论】:
-
您的示例根本不清楚输出数组是如何从导入数组派生的。请用文字解释这个想法,因为你的例子不清楚。你想用列表中最小的数字替换数组第一列中的最小数字,用第二小的数字替换第二小的数字,等等?如果是这样,是否保证数组和列表中的第一列按非降序排序?
-
输出数组是我打算从
x得到的 -
显示完整的
error。还要注意数组的 dtype。我猜它们是字符串 dtype。 -
编辑了问题
-
如果稍后出现另一个
2,它应该与第一次出现2共享相同的值,还是不同的值?
标签: python python-3.x numpy