How to replace elements of a DataFrame from other indicated columns

Viewed 272

I have a DataFrame like:

df = pd.DataFrame([{'v1':'a', 'v2':'b', 'v3':'1'},
                   {'v1':'2', 'v2':'c', 'v3':'d'}])

or

  v1 v2 v3
0  a  b  1
1  2  c  d

When the contents of a column/row is '1', '2' or '3', I would like to replace its contents with the corresponding item from the column indicated. I.e., in the first row, column v3 has value "1" so I would like to replace it with the value of the first element in column v1. Doing this for both rows, I should get:

  v1 v2 v3
0  a  b  a
1  c  c  d

I can do this with the following code:

for i in range(3):
    for j in range(3):
        df.loc[df['v%d' % (i+1)]==('%d' % (j+1)),'v%d' % (i+1)]= \
            df.loc[df['v%d' % (i+1)]==('%d' % (j+1)),'v%d' % (j+1)]

Is there a less cumbersome way to do this?

4 Answers
Related