【问题标题】:Remove rows from dataframe if it has partial match with other rows for specific columns如果与特定列的其他行部分匹配,则从数据框中删除行
【发布时间】:2021-11-30 00:48:39
【问题描述】:

我想删除数据帧中开始和结束字符索引部分重叠的行。

详情:

我有两个句子,我从中提取了一些实体并将它们组织在一个数据框中。

句子:

| id  |            sentence                          |
| --- |             ---                              |
|  1  | Today is a very sunny day and sun is shining |
|  2  | I bought the red balloon and playing with it |

我的提取实体的数据框如下所示:

| id |     data        | start_char_index | end_char index | token_position |
| ---| --------------  | ---------------- | -------------- | -------------- |
| 1  | very sunny day  |      11          |      26        |  [4,5,6]       |
| 1  | shining         |      37          |      45        |    [10]        |
| 1  | sunny           |      16          |      21        |    [5]         |
| 2  | the red balloon |      9           |      25        |   [3,4,5]      | 
| 2  | playing         |      29          |      37        |     [7]        |
| 2  | red             |      13          |      16        |     [4]        |

附:在这个token位置是文本中特定token的索引(从1开始)

现在,对于 id 1。我们看到“非常晴天”和“晴天”是部分重叠的(它们的开始和结束字符索引以及标记位置都重叠) id 2 也是如此,其中“红色气球”和“红色”具有重叠的红色,我想删除两个不同 id 中重叠较小的行“阳光”和“红色”。

我考虑过将它们按 id 分组,然后通过将开始和结束字符索引(或标记位置)存储在字典中来删除这些记录,但如果我有很多数据行和很多 id,那将是非常慢。 我还阅读了有关 IntervalTree 的信息,但我无法非常有效地将它用于部分重叠。

那么您能否为此提出一些解决方案?

最终的输出数据框应如下所示:

| id |     data        | start_char_index | end_char index | token_position |
| ---| --------------  | ---------------- | -------------- | -------------- |
| 1  | very sunny day  |      11          |      26        |  [4,5,6]       |
| 1  | shining         |      37          |      45        |    [10]        |
| 2  | the red balloon |      9           |      25        |   [3,4,5]      | 
| 2  | playing         |      29          |      37        |     [7]        |

提前感谢您的帮助:)

【问题讨论】:

  • balloon 和 sunny 的位置如何?
  • 我认为id指的是数据来自的字符串,所以sunny是字符串1的位置5,气球是字符串2的位置5
  • 是的,正如Patrick指出的那样,token_position表示id列指示的各个句子中token的索引

标签: python pandas list dataframe


【解决方案1】:

除了 Mortz 的回答之外,我还尝试了 pandas IntervalArray 和重叠,这对我来说工作得更快。把它放在这里给任何可能觉得它有用的人(致谢:https://stackoverflow.com/a/69336914/15941713):

from intervaltree import Interval, IntervalTree
def drop_subspan_duplicates(df):

   idx1 = pd.arrays.IntervalArray.from_arrays(
                          df['start'], 
                          df['end'], 
                          closed='both')

  df['wrd_id'] = df.apply(lambda x : df.index[idx1.overlaps(pd.Interval(x['start'], x['end'], closed='both'))][0],axis=1)
  df= df.drop_duplicates(['wrd_id'],keep='first')
  df.drop(['wrd_id'],axis=1,inplace=True)
  return df

output = data.groupby('id').apply(drop_subspan_duplicates)

如果希望避免数据帧操作,也可以参考this 回答以解决该问题

【讨论】:

    【解决方案2】:

    我不确定DataFrame 是解决此问题的最佳结构 - 但这是一种方法

    df = pd.DataFrame({'id': [1, 1, 1], 'start': [11, 20, 16], 'end': [18, 35, 17]})
    
    # First we construct a range of numbers from the start and end index
    df.loc[:, 'range'] = df.apply(lambda x: list(range(x['start'], x['end'])), axis=1)
    
    # Next, we "cumulate" these ranges and measure the number of unique elements in the cumulative range at each row 
    df['range_size'] = df['range'].cumsum().apply(lambda x: len(set(x)))
    
    # Finally we check if every row adds anything to the cumulative range - if a new row adds nothing, then we can drop that row
    df['range_size_shifted'] = df['range'].cumsum().apply(lambda x: len(set(x))).shift(1)
    df['drop'] = df.apply(lambda x: False if pd.isna(x['range_size_shifted']) else not int(x['range_size'] - x['range_size_shifted']), axis=1)
    
    print(df)
    #   id  start  end   drop
    #0   1     11   18  False
    #1   1     20   35  False
    #2   1     16   17   True
    

    如果您想分别为每个组执行此操作 -

    for key, group in df.groupby('id'):
        group.loc[:, 'range'] = group.apply(lambda x: list(range(x['start'], x['end'])), axis=1)
        group['range_size'] = group['range'].cumsum().apply(lambda x: len(set(x)))
        group['range_size_shifted'] = group['range'].cumsum().apply(lambda x: len(set(x))).shift(1)
        group['drop'] = group.apply(lambda x: False if pd.isna(x['range_size_shifted']) else not int(x['range_size'] - x['range_size_shifted']), axis=1)
        print(group)
    

    【讨论】:

    • 虽然这解决了我的问题,但它在大数据大小上效率不高。有没有办法优化这个解决方案?
    • 您需要为问题提供更多上下文 - 您从哪里读取数据?数据有多大?你有使用熊猫和数据框吗?与哪种替代方案相比,此解决方案次优?
    • 数据大小以数据框本身的形式以百万计,所以我必须使用熊猫和数据框。我使用了区间树重叠函数,对于相同的数据,区间树函数比这里的解决方案更快。请注意,通过优化和次优,我只是比较了数据的处理速度
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-14
    • 2011-10-02
    • 1970-01-01
    相关资源
    最近更新 更多