0

Having 2 columns , I want to map values from column3 to column1 if there is no value in column1, if column3 is also blank then no value will be mapped.

Input Data

column1    column2    column3

2225        India      2227
             UK        35604
32578       USA        38956
            Dubai
7528        Bhutan    
            India      37890

Expected Output:

column1    column2    column3

2225        India      2227
35604        UK        35604
32578       USA        38956
            Dubai
7528        Bhutan    
37890       India      37890

Script i am trying to use :

if df['column1'] = 'NaN':
   df['column1'] = df['column3']

Please Suggest How i can map values from column3 to column1 if column1 is blank.

11
  • 10
    df['column1'] = df['column1'].fillna(df['column3'])? Commented May 5, 2021 at 17:54
  • @QuangHoang - Thanks for the Answer, df['column1'] = df['column1'].fillna(df['column3']) maps the value from Column3 to column1 if column1 is blank, How i can map value from column3 to column1 if both the column values are different, What modification can e done in the above line. Commented May 10, 2021 at 16:17
  • df['column1'] = df['column3'] ??? Commented May 10, 2021 at 16:19
  • @QuangHoang - I am looking to modify the line "df['column1'] = df['column1'].fillna(df['column3'])" with one more condition as if df['column1'] != df['column3'] , I need to update the value from column3 to column1, Please suggest. Commented May 10, 2021 at 16:22
  • I don't get your question, where df['col1'] is nan, then it is already different from df['col3']. Where it is not nan, you also want to replace by the value in column3? Then that's just what I posted. Commented May 10, 2021 at 16:25

1 Answer 1

1

You can also try np.where

import pandas as pd
import numpy as np

df = pd.DataFrame({'column1': {0: 2225, 1: np.nan, 2: 32578, 3: np.nan, 4: 7528, 5: np.nan},
                   'column2': {0: 'India', 1: 'UK', 2: 'USA', 3: 'Dubai', 4: 'Bhutan', 5: 'India'},
                   'column3': {0: 2227.0, 1: 35604.0, 2: 38956.0, 3: np.nan, 4: np.nan, 5: 37890.0}})

df['column1'] = np.where(df['column1'].isna(), df['column3'], df['column1'])
print(df)

   column1 column2  column3
0   2225.0   India   2227.0
1  35604.0      UK  35604.0
2  32578.0     USA  38956.0
3      NaN   Dubai      NaN
4   7528.0  Bhutan      NaN
5  37890.0   India  37890.0
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.