0

I'd like to replace the values in valcol with the values in the column which is the value. Suppose you have df looking something like below:

  col1 col2 col3 valcol
0    a    d    g   col1
1    b    e    h   col1
2    c    f    i   col2

I'd like the valcol_new to become this:

  col1 col2 col3 valcol valcol_new
0    a    d    g   col1          a
1    b    e    h   col1          b
2    c    f    i   col2          f

How would one do this?

df for testing:

df = pd.DataFrame({'col1': ['a', 'b', 'c'], 'col2': ['d', 'e', 'f'], 'col3': ['g', 'h', 'i'], 'valcol': ['col1', 'col1', 'col2']})
destinychoice
  • 45
  • 3
  • 15

1 Answers1

1

You can do this by enumerate() method and list comprehension and loc[] accessor:

df['valcol']=[df.loc[x,y] for x,y in enumerate(df['valcol'])]

Now if you print df you will get your desired output:

    col1    col2    col3    valcol
0   a       d       g       a
1   b       e       h       b
2   c       f       i       f
Anurag Dabas
  • 23,866
  • 9
  • 21
  • 41