【问题标题】:Removing a number of consecutive rows that fulfills a certain condition删除满足特定条件的多个连续行
【发布时间】:2021-11-22 20:56:40
【问题描述】:

如果行中的所有值都小于 1 并且超过例如 4 行,我正在尝试删除数据框中的连续行。

假设我们有一个专栏[0.1, 0, 5, 4, 0.2, 0.1, 0, 0, 0, 4, 9, 10]。然后我想只删除中间部分[0.2, 0.1, 0, 0, 0] 并离开[0.1, 0, 5, 4, 4, 9, 10]。问题是我可以通过使用 for 循环轻松做到这一点,但是我正在处理超过 300 万个数据点,而且花费的时间太长。因此,我正在寻找一种在 R 中利用矢量化的解决方案。有人知道我可以使用什么功能吗?

提前致谢!

【问题讨论】:

    标签: r dataframe row vectorization


    【解决方案1】:

    您可以尝试对数据集执行卷积/相关。如果 4 个连续行中的所有元素都小于 1,则它们的总和小于 4 * mm 是数据集的列数。然后,正确地对结果进行上采样是一个问题。这是一个完整的示例,带有 NumPy 数组(您可以使用 df.to_numpy() 轻松地从 DataFrame 中提取):

    import numpy as np
    """
    Notation: row whose elements are all < 1, will be called "target row"
    Task: Remove every target row in a cluster of 4 consecutive target rows
    
    Input: 11 x 5 dataset with target rows [0, 1, 2, 3, 4, 7]
    Output: pruned dataset with rows [5, 6, 7, 8, 9, 10]
    (Note that target row 7 must be kept because it's separated from the others)
    """
    
    # Input
    n, m = 11, 5
    ar = np.random.rand(n, m)
    ar[[5, 6, 8, 9, 10]] += 1.
    min_rows = 4
    
    # Find all target rows
    sums = (ar.sum(axis=1) < ar.shape[1]).astype(np.float32)
    print(f"    Sums: {sums}")
    
    # Find centers of clusters with 4 consecutive target rows
    kernel = np.ones((min_rows,))
    output = np.correlate(sums, kernel, mode="same")
    print(f"  Output: {output}")
    
    mask = output == min_rows
    print(f"    Mask: {mask.astype(np.float32)}")
    
    
    # Find all elements in the clusters
    mask_ids = np.nonzero(mask)[0]
    center = min_rows // 2
    rng = np.arange(-center, center + (min_rows % 2 != 0), dtype=np.int32)
    
    
    ids = (rng + mask_ids.reshape(-1, 1)).ravel()
    mask[ids] = True
    print(f"New Mask: {mask.astype(np.float32)}")
    
    # mask the dataset
    ar = ar[~mask]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-22
      • 1970-01-01
      相关资源
      最近更新 更多