0

I have a pandas data frame and y have 2 columns, A and B. Column A has some null values so I want to create a column C like this, if A have a null value then take the value of B, else take the value of A. I am using this code but it´s not working:

if data['A'] is None: data['C'] = data['B'] else: data['C'] = data['A'] 

2 Answers 2

1

Use fillna -

data['C'] = data['A'].fillna(data['B']) 
Sign up to request clarification or add additional context in comments.

Comments

0

If you are using the exact sample code, you are missing a Semi-quotation mark on line 2 after C, otherwise you can do this:

Use isnull instead of is None

import pandas as pd data = pd.DataFrame({'A': [1,None], 'B': [3, 4]}) if data['A'].isnull: data['C'] = data['B'] else: data['C'] = data['A'] print (data['C'].values) 

Output [3 4]

Here is a link to pandas official doc, DataFrame.isnull

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.