在其他列中查找列值匹配的索引

时间:2021-07-18 19:05:57

标签: python pandas indexing

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

   a  b
0  5  7
1  3  5
2  7  1

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

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

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

1 个答案:

答案 0 :(得分:2)

带有 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
相关问题