【问题标题】:How can I add a column of one data frame to another based on the nearest identifier?如何根据最近的标识符将一个数据框的一列添加到另一个数据框?
【发布时间】:2019-09-06 20:09:08
【问题描述】:

问题:

  1. 我有一个包含测量值的数据框 foo 和一个 common_step 列,其中包含指示每行测量时间的整数。

  2. 我有第二个数据框,它还包含一个 common_step 列和一个 bar_step 列。它在两个整数步长之间进行转换。

  3. 我想将bar_step 作为一列添加到foo。但是,两个数据框的common_step 值没有对齐。

  4. 因此,对于foo 中的每一行,我想在bar 中找到最接近global_step 的行并将其bar_step 添加到foo 行。

  5. 我找到了一种方法来做到这一点。但是,解决方案非常缓慢。这是因为对于foo 中的每一行,它都会搜索bar 中的所有行以找到与global_step 最接近的行。

foo.sort_values('common_step', inplace=True)
bar.sort_values('common_step', inplace=True)
def find_nearest(foo_row):
  index = abs(bar.common_step - foo_row.common_step).idxmin()
  return bar.loc[index].bar_step
foo['bar_step'] = scores.apply(find_nearest, axis=1)

问题:

  • 如何将最接近的匹配 bar_step 添加到具有二次运行时间的 foo 数据表?
  • 此外,最好有一个标志来选择最近但较小 global_step的行。

【问题讨论】:

标签: python pandas


【解决方案1】:

正如@QuangHoang 在评论中建议的那样,merge_asof 这样做了。此外,第二个数据框不应包含其他列,以免干扰第一个中的现有列:

foo.sort_values('common_step', inplace=True)
bar.sort_values('common_step', inplace=True)
bar = bar[['bar_step', 'common_step']]
foo = pandas.merge_asof(foo, bar, on='common_step', direction='backward')

direction 参数指定是使用最近的低匹配、最近的高匹配还是考虑两个方向的最近匹配。来自文档:

  • “向后”搜索选择右侧 DataFrame 中“on”键小于或等于左侧键的最后一行。
  • “向前”搜索选择右侧 DataFrame 中“on”键大于或等于左侧键的第一行。
  • “最近”搜索会选择右侧 DataFrame 中“on”键在绝对距离上与左侧键最近的行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-29
    相关资源
    最近更新 更多