【问题标题】:Find index where column value is matched in other column查找列值在其他列中匹配的索引
【发布时间】:2023-04-01 11:42:01
【问题描述】:

我有一个包含两个整数列的数据框,例如:

   a  b
0  5  7
1  3  5
2  7  1

我需要一个包含索引的附加列,其中列a 的值等于当前行的列b 的值。即:b=7 与索引2 处的a=7 匹配,b=5 与索引a=5 处的a=5 匹配,b=1 不匹配。期望的输出:

   a  b  c
0  5  7  2
1  3  5  0
2  7  1  NaN

永远不会有多个行满足条件。

【问题讨论】:

  • a 列中是否存在重复项?
  • @Psidom a 中有重复值,但这些值不会出现在 b

标签: python pandas indexing


【解决方案1】:

searchsorted 选项:

# sort column a and find candidate position of values in b in a
df.sort_values('a', inplace=True)
pos = df.a.searchsorted(df.b)

# handle edge case when the pos is out of bound
pos[pos == len(pos)] = len(pos) - 1

# assign the index to column as c and mark values that don't match as nan
df['c'] = df.index[pos]
df.loc[df.a.loc[df.c].values != df.b.values, 'c'] = np.nan

df.sort_index()

#   a  b    c
#0  5  7  2.0
#1  3  5  0.0
#2  7  1  NaN

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-16
    • 2023-03-24
    • 2017-02-23
    相关资源
    最近更新 更多