python 翻转NumPy矩阵中的列值,同时保留NaN值并考虑重复值

o4hqfura  于 2023-02-18  发布在  Python
关注(0)|答案(1)|浏览(131)

我想翻转NumPy矩阵每列中的值。该函数应保留输出矩阵中的NaN值,重复值应替换为翻转后的对应值。以下是输入和输出矩阵的示例:

A = np.array([
    [1.0,2.0,3.0],
    [np.nan,2.0,np.nan],
    [2.0,1.0,np.nan],
    [3.0,np.nan,1.0]
    ])

A_flipped = np.array([
    [3.0,1.0,1.0],
    [np.nan,1.0,np.nan],
    [2.0,2.0,np.nan],
    [1.0,np.nan,3.0]
    ])
htrmnn0y

htrmnn0y1#

New-flip =根据排序替换中值附近的值

def median_flip_1d(arr):
    new = np.empty_like(arr)
    srt = np.sort(arr)
    for i in range(srt.shape[0]):
        new[arr==srt[i]] = srt[srt.shape[0]-i-1]
    return new
def col_median_flip_2d(A):
    A_flipped = np.copy(A)
    for col in A_flipped.T:
        col[~np.isnan(col)] = median_flip_1d(col[~np.isnan(col)])
    return A_flipped

单函数

def col_median_flip_2d(A):
    A_flipped = np.copy(A)
    for col in A_flipped.T:
        arr = col[~np.isnan(col)]
        new = np.empty_like(arr)
        srt = np.sort(arr)
        for i in range(srt.shape[0]):
            new[arr==srt[i]] = srt[srt.shape[0]-i-1]
        col[~np.isnan(col)] = new
    return A_flipped

旧-翻转=镜像

A_flipped = np.empty_like(A) #empty array with shape and dtype of A
A_flipped[np.isnan(A)] = np.nan #set np.nan where A is np.nan
temp = np.flipud(A) #temp normal flip array
A_flipped[np.invert(np.isnan(A))] = temp[np.invert(np.isnan(temp))] #assign values

相关问题