【问题标题】:Pandas select rows when column value within range from another row column value with group filter当列值在另一个行列值的范围内时,Pandas 使用组过滤器选择行
【发布时间】:2018-07-23 23:43:03
【问题描述】:

我想扩展我在link to question 上提出的问题

场景比较复杂,所以我认为那里的解决方案不适合

我正在尝试使用以下格式从数据帧(100k-500k 行)创建子集

d = {'time':[1,2,3,5,7,9,9.5,10], 'val':['not','match','match','not','not','match','match','match'],
    'group':['a','a','b','b','b','a','a','c']}
df = pd.DataFrame(d)
print(df)
  group  time    val
0     a   1.0    not
1     a   2.0  match
2     b   3.0  match
3     b   5.0    not
4     b   7.0    not
5     a   9.0  match
6     a   9.5  match
7     c  10.0  match

当时间在有限范围内时,我想选择一个包含所有行的子集。例如,如果 range 为

  • row0 具有有效的时间差异 (row1-row0),但它们在同一组中。
  • row1 具有有效的时间差异 (row2-row1),并且每个都有不同的组。
  • row5 具有有效的时间差异 (row7-row5),并且每个都有不同的组。
  • row6 具有有效的时间差异 (row7-row6),并且每个都有不同的组。

还有我想要的输出

  group  time    val
1     a   2.0  match
2     b   3.0  match
5     a   9.0  match
6     a   9.5  match
7     c  10.0  match

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    这适用于您的示例,希望适用于您的数据:

    df.loc[((df['time'].diff() <= 1)|(df['time'].diff(-1) >= -1))&((df['group']!=df['group'].shift(-1).fillna(df['group']))|(df['group']!=df['group'].shift(1).fillna(df['group'])))]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多