使用Nan填充而不是零的numpy上三角矩阵(Make a numpy upper triangular matrix padded with Nan instead of zero)

编程入门 行业动态 更新时间:2024-10-08 13:37:47
使用Nan填充而不是零的numpy上三角矩阵(Make a numpy upper triangular matrix padded with Nan instead of zero)

我生成一个matplotlib 3d曲面图。 我只需要在图上看到矩阵的上三角形的一半,因为另一半是多余的。

np.triu()使冗余的矩阵零点的一半,但我更喜欢如果我能使它们成为Nans,那么这些单元根本不会在曲面图上出现。

用NaN而不是零填充pythonic的方式是什么? 我无法使用NaN进行搜索和替换0,因为零会出现在我想要显示的合法数据中。

I generate a matplotlib 3d surface plot. I only need to see the upper-triangular half of the matrix on the plot, as the other half is redundant.

np.triu() makes the redundant half of the matrix zeros, but I'd prefer if I can make them Nans, then those cells don't show up at all on the surface plot.

What would be a pythonic way to fill with NaN instead of zeros? I cannot do a search-and-replace 0 with NaN, as zeros will appear in the legitimate data I want to display.

最满意答案

您可以使用numpy.tril_indices()将NaN值分配给较低的三角形,例如:

>>> import numpy as np >>> m = np.triu(np.arange(0, 12, dtype=np.float).reshape(4,3)) >>> m array([[ 0., 1., 2.], [ 0., 4., 5.], [ 0., 0., 8.], [ 0., 0., 0.]]) >>> m[np.tril_indices(m.shape[0], -1)] = np.nan >>> m array([[ 0., 1., 2.], [ nan, 4., 5.], [ nan, nan, 8.], [ nan, nan, nan]])

You can use numpy.tril_indices() to assign the NaN value to lower triangle, e.g.:

>>> import numpy as np >>> m = np.triu(np.arange(0, 12, dtype=np.float).reshape(4,3)) >>> m array([[ 0., 1., 2.], [ 0., 4., 5.], [ 0., 0., 8.], [ 0., 0., 0.]]) >>> m[np.tril_indices(m.shape[0], -1)] = np.nan >>> m array([[ 0., 1., 2.], [ nan, 4., 5.], [ nan, nan, 8.], [ nan, nan, nan]])

更多推荐

本文发布于:2023-07-30 14:57:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1338786.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:矩阵   而不是   numpy   Nan   padded

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!