繁体   English   中英

对于带有间隙的网格数据,是否有 np.reshape 的替代方法?

[英]Is there an alternative to np.reshape for gridded data with gaps?

我有一个数据集,它是网格数据,它已被展平为 x、y 和 z 数据的单列,但我想将其重新放入网格中以对其运行 2D 傅立叶变换。 不幸的是,围绕网格年龄的数据存在一些差距。

对于常规网格,使用np.reshape可以将这些数据放回网格中,但由于存在间隙,这将不起作用。 是否有类似的功能可以让我重塑和添加 nans?

示例数据集(尽管我的数据有超过 80,000 个条目)。

x = np.array([0, 1, 2 , 3, -1, 0, 1, 2, -1, 0, 1, -3, -2,-1,0])
y = np.array([0,1,2, 3, 1, 2,3,4, 3,4, 5, 3, 4,5,6])

我想进入表格:

x = array([[ 0.,  1.,  2.,  3.],
   [-1.,  0.,  1.,  2.],
   [nan, -1.,  0.,  1.],
   [-3., -2., -1.,  0.]])

y = array([[ 0.,  1.,  2.,  3.],
       [ 1.,  2.,  3.,  4.],
       [nan,  3.,  4.,  5.],
       [ 3.,  4.,  5.,  6.]])

此数据集绘制为散点图

这是部分解决方案。 目前,它假定网格的左侧或右侧缺少数据(即它还不能处理顶部和底部)。 它还假设数据跨列增加(否则,您只需将>交换为<if / else语句的主体),并且跨行的更改小于从第一列到最后一栏(如果这不是真的,那么你手上的问题就更难了)。 根据数据的生成方式,您可能还想用条件替换==来测试被比较的两个值是否相对接近/小于行末尾值之间的差异。

import numpy as np

x = np.array([0, 1, 2 , 3, -1, 0, 1, 2, -1, 0, 1, -3, -2,-1,0])

def vector_to_array(x, verbose=False):
    # Reformat into list of lists
    x_grid_list = [[x[0]]]
    for i in x[1:]:
        if i > x_grid_list[-1][-1]:
            x_grid_list[-1].append(i)
        else:
            x_grid_list.append([i])
    
    # Calculate width and height
    height = len(x_grid_list)
    width = max(len(i) for i in x_grid_list)

    # Fill in missing data
    for row_ind in range(1, len(x_grid_list[1:])):
        row = x_grid_list[row_ind]
        if len(row) < width:
            if row[0] == x_grid_list[row_ind - 1][0]:
                # Missing data is on the left hand side
                x_grid_list[row_ind] = [np.nan] + row
            else:
                # Missing data is on the right hand side
                x_grid_list[row_ind] = row + [np.nan]

    # Convert to np array, print if verbose, and return
    x_array = np.array(x_grid_list)
    if verbose:
        print(x)
        print(x_grid_list)
        print(x_array)
    return x_array

x = np.array([0, 1, 2 , 3, -1, 0, 1, 2, -1, 0, 1, -3, -2,-1,0])
vector_to_array(x, True)
print("*" * 50)
x = np.array([0, 1, 2 , 3, -1, 0, 1, 2, -2, -1, 0, -3, -2,-1,0])
vector_to_array(x, True)

输出:

[ 0  1  2  3 -1  0  1  2 -1  0  1 -3 -2 -1  0]
[[0, 1, 2, 3], [-1, 0, 1, 2], [nan, -1, 0, 1], [-3, -2, -1, 0]]
[[ 0.  1.  2.  3.]
 [-1.  0.  1.  2.]
 [nan -1.  0.  1.]
 [-3. -2. -1.  0.]]
**************************************************
[ 0  1  2  3 -1  0  1  2 -2 -1  0 -3 -2 -1  0]
[[0, 1, 2, 3], [-1, 0, 1, 2], [-2, -1, 0, nan], [-3, -2, -1, 0]]
[[ 0.  1.  2.  3.]
 [-1.  0.  1.  2.]
 [-2. -1.  0. nan]
 [-3. -2. -1.  0.]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM