我生成一个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]])更多推荐
发布评论