如果满足条件,则替换 Numpy 中的行 - 变体

发布于 2025-01-17 14:35:17 字数 942 浏览 2 评论 0原文

我仍在弄清楚 Numpy 语法!我有一些可行的方法,但必须有一种更简洁的方法来执行此任务。在下面的示例中,我将数组的选定行替换为新条目,其中条件仅针对一个元素。

import numpy as np
big_array = np.random.randint(10, size=(5, 2)) # multi-dimension array
print(big_array)
bad_values = np.less_equal(big_array[:,0], 4)  # condition value in one dimension
bad_rows = np.nonzero(bad_values)[0]           # indexes to change, e.g. rows
print(f'these are the rows to replace {bad_rows}')
new_rows = np.random.randint(10, size=((bad_rows.size),2))+10  # smaller multi-dim array
np.put(big_array[:,0],bad_rows,y[:,0])   # should be a single line to combine this
np.put(big_array[:,1],bad_rows,y[:,1])   # with this?
print(big_array)

我想要的示例输出可能看起来像

[[2 4]
 [5 9]
 [6 6]
 [6 7]
 [0 6]]
 these are the rows to replace [0 4]
 [[16 17]
 [ 5  9]
 [ 6  6]
 [ 6  7]
 [18 17]]

我不知道如何为不同维度的参数格式化 put 。这看起来应该是一句单行话。 (如果我尝试where,我会收到广播长度问题。)我错过了什么?

I am still figuring out Numpy syntax! I have something that works but there must be a more concise way to perform this task. In the example below, I replace selected rows of an array with new entries, where the condition is just on one element.

import numpy as np
big_array = np.random.randint(10, size=(5, 2)) # multi-dimension array
print(big_array)
bad_values = np.less_equal(big_array[:,0], 4)  # condition value in one dimension
bad_rows = np.nonzero(bad_values)[0]           # indexes to change, e.g. rows
print(f'these are the rows to replace {bad_rows}')
new_rows = np.random.randint(10, size=((bad_rows.size),2))+10  # smaller multi-dim array
np.put(big_array[:,0],bad_rows,y[:,0])   # should be a single line to combine this
np.put(big_array[:,1],bad_rows,y[:,1])   # with this?
print(big_array)

sample output that I want might look like

[[2 4]
 [5 9]
 [6 6]
 [6 7]
 [0 6]]
 these are the rows to replace [0 4]
 [[16 17]
 [ 5  9]
 [ 6  6]
 [ 6  7]
 [18 17]]

I don't know how to format put for arguments with different dimensions. This seems like it should be a one-liner. (If I try where I get length issues broadcasting.) What am I missing?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文