5

Say I have two columns, A and B, in my dataframe:

A B 1 NaN 2 5 3 NaN 4 6 

I want to get a new column, C, which fills in NaN cells in column B using values from column A:

A B C 1 NaN 1 2 5 5 3 NaN 3 4 6 6 

How do I do this?

I'm sure this is a very basic question, but as I am new to Pandas, any help will be appreciated!

3 Answers 3

6

You can use combine_first:

df['c'] = df['b'].combine_first(df['a']) 

Docs: http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.Series.combine_first.html

Sign up to request clarification or add additional context in comments.

2 Comments

really elegant, this is the best solution!
most powerful way to do
5

You can use where which is a vectorized if/else:

df['C'] = df['A'].where(df['B'].isnull(), df['B']) A B C 0 1 NaN 1 1 2 5 5 2 3 NaN 3 3 4 6 6 

3 Comments

Thanks very much for pointing out the where clause, which seems useful for many other purposes as well. I have just looked at the documentation for it here: pandas.pydata.org/pandas-docs/version/0.17.0/generated/…. I am wondering what the inplace argument does. The description is somewhat obscure. Could anyone enlighten me?
you can simplify to this: df['C'] = df.A.where(df.B.isnull(), df.B) as isnull is available for df and series, also I wouldn't encourage the practice of accessing columns as attributes as it can lead to strange behaviour, better to do this df['C'] = df['A'].where(df['B'].isnull(), df['B'])
I edit my post, you are right on the accessing cols by attribute
2
df['c'] = df['b'].fillna(df['a']) 

So what .fillna will do is it will fill all the Nan values in the data frame We can pass any value to it Here we pass the value df['a'] So this method will put the corresponding values of 'a' into the Nan values of 'b' And the final answer will be in 'c'

1 Comment

This answer would benefit from a brief explanation of what .fillna() does, and perhaps a documentation link.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.