Home > Software design >  How to get indices of rows in a given column in which a value from a different given column appears?
How to get indices of rows in a given column in which a value from a different given column appears?

Time:11-25

I have two columns. The first one is longer and has multiple values such as:

0 'A'
1 'B'
2 'B'
3 'C'
4 'A'
5 'A'

All the values in the first column are listed in the second column:

0 'A'
1 'B'
2 'C'

The result I want is to have a list/series/column whatever of indecies of the values from the first column in the second column, as such:

0 'A' 0
1 'B' 1
2 'B' 1
3 'C' 2
4 'A' 0
5 'A' 0

Edit: in the actual problem that I have the number of values is very big so listing them by hand is not an option

CodePudding user response:

Working with pandas Series:

new_s = s1.map(dict(zip(s2, s2.index)))

CodePudding user response:

If both columns are Dataframes:

try this:

maper = dict(df2.reset_index().values[:, ::-1])
out = df1.assign(result=df1.replace(maper))
print(out)
  • Related