Home » Python » python – Map Dataframe Column-Exceptionshub

python – Map Dataframe Column-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I have a dataframe like this:

  col1 col2 col3
  | a | 1 | 2 |

What I want to do is map each row to replace the col3 with this function

def winner (col2, col3, col1):
    if(col1 == "a"):
        return col2
    elif(col1 == "D"):
        return col3
    else:
        return "X"

I tried to map but I can’t

Output:

  col1 col2 col3
  | a | 1 | 1 |

Can anybody help me?

How to&Answers:

First you have to define your mapping function, you can do it like this :

def winner (raw):
    if(raw['col1'] == "a"):
        return raw['col2']
    elif(raw['col1'] == "D"):
        return raw['col3']
    else:
        return "X"

Then you can use the pandas.apply function to apply your mapping function :

df['col3'] = df.apply(lambda row : winner(row),axis=1)

And now you have a nice little brand new dataframe 🙂 !