numpy:替换重新数组中的值
我对 numpy 很陌生,我正在尝试替换重新数组中的值。所以我有这个数组:
import numpy as np
d = [('1', ''),('4', '5'),('7', '8')]
a = np.array(d, dtype=[('first', 'a5'), ('second', 'a5')])
我想做这样的事情:
ind = a=='' #Replace all blanks
a[ind] = '12345'
但这不能正常工作。我能够做到这一点:
col = a['second']
ind = col=='' #Replace all blanks
col[ind] = '54321'
a['second'] = col
这有效,但我宁愿有一种方法可以在整个重新排列中做到这一点。有人有更好的解决方案吗?
I'm pretty new to numpy, and I'm trying to replace a value in a recarray. So I have this array:
import numpy as np
d = [('1', ''),('4', '5'),('7', '8')]
a = np.array(d, dtype=[('first', 'a5'), ('second', 'a5')])
I would like to do something like this:
ind = a=='' #Replace all blanks
a[ind] = '12345'
but that doesnt work properly. I was able to do this:
col = a['second']
ind = col=='' #Replace all blanks
col[ind] = '54321'
a['second'] = col
Which works, but I would rather have a way to do it over the entire recarray. Anyone have a better solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
据我所知,numpy 的“逐元素”操作(使用它您可以一次对数组的所有元素执行某些函数而无需循环)不适用于重新数组。您只能对各个列执行此操作。
如果你想使用重新排列,我认为最简单的解决方案是循环不同的列,虽然你想要另一个解决方案,但你可以像这样自动完成:
但也许你应该考虑是否真的需要重新排列,并且不能只需使用普通的 ndarray 即可。当然,如果您只有一种数据类型(如示例中所示),那么唯一的优点是列名。
The "element-by-element" operations of numpy (with wich you can perform some function on all elements of the array at once without a loop) don't work with recarrays as far as I know. You can only do that with the individual columns.
If you want to use recarrays, I think the easiest solution is to loop the different columns, although you wanted another solution, but you can do it pretty automatic like this:
But maybe you should consider if you really need recarrays, and can't just use normal ndarray. Certainly if you have only one data type (as in the example), then the only advantage are the column names.
一种可能的解决方案:
One possible solution: