Lostsoul
Lostsoul

Reputation: 25999

Swapping values between two pandas columns

How can I swap values in a dataframe based on a defined condition?

Given:

DF[['Exchange','predictions']]

Exchange    predictions
0   PINK    <UNK>
1   PINK    <UNK>
2   PINK    <UNK>
3   PINK    <UNK>
4   PINK    <UNK>
... ... ...
490541  NASDAQ  PINK
490542  NaN PINK
490543  NASDAQ  PINK
490544  NaN PINK
490545  NASDAQ  PINK

I would like Exchange replaced with value in predictions only if Exchange value is NaN and Prediction value is not < UNK >.

Upvotes: 0

Views: 52

Answers (1)

BENY
BENY

Reputation: 323226

Let us try fillna with partial condition Series

df.Exchange.fillna(df.loc[df['predictions'].ne('<UNK>'), 'predictions'], inplace=True)
df
Out[210]: 
       Exchange predictions
0          PINK       <UNK>
1          PINK       <UNK>
2          PINK       <UNK>
3          PINK       <UNK>
4          PINK       <UNK>
         ...         ...
490541   NASDAQ        PINK
490542     PINK        PINK
490543   NASDAQ        PINK
490544     PINK        PINK
490545   NASDAQ        PINK

Upvotes: 1

Related Questions