[英]Python: mask a numpy.ndarray with another numpy.ndarray with elegant solution
I have two numpy.ndarray and i found a not elegant solution (using more than 4 lines code) to mask the data2 with data1. 我有两个numpy.ndarray,我发现一个不优雅的解决方案(使用超过4行代码)用data1屏蔽data2。 I am asking an elegant solution , saving line to do:
我问一个优雅的解决方案 ,保存线来做:
example. 例。
data1 = np.array([[1,2,np.nan,4,5],[np.nan,7,np.nan,9,np.nan],[11,12,13,14,np.nan],[np.nan,17,np.nan,19,20]])
data2 = np.ones((6, 4))
print data1
[[ 1. 2. nan 4. 5.]
[ nan 7. nan 9. nan]
[ 11. 12. 13. 14. nan]
[ nan 17. nan 19. 20.]]
>>> print data2
[[ 1. 1. 1. 1.]
[ 1. 1. 1. 1.]
[ 1. 1. 1. 1.]
[ 1. 1. 1. 1.]
[ 1. 1. 1. 1.]
[ 1. 1. 1. 1.]]
the result i wish to have is: 我希望得到的结果是:
[[ 1. 2. 1 4. 5.]
[ 1 7. 1 9. 1]
[ 11. 12. 13. 14. 1]
[ 1 17. 1 19. 20.]]
in other words, where data1 is nan the value of data2 换句话说,data1是data2的值
Thanks in advance for help and suggestions. 在此先感谢您的帮助和建议。 I did this with more than 4 lines of code
我用超过4行代码完成了这项工作
Assuming you mean to have data1 and data2 as arrays of the same size (which would change your example to read): 假设你的意思是将data1和data2作为相同大小的数组(这会改变你的例子来读取):
data2 = np.ones((4, 5))
A one line approach is: 一线方法是:
data1[np.isnan(data1)] = data2[np.isnan(data1)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.