How to combine two columns in a data frame in Pandas?

Let's say I have two columns: A and B in my data frame:

AB 1 NaN 2 5 3 NaN 4 6 

I want to get a new column C that fills the NaN cells in column B using the values ​​from column A:

 ABC 1 NaN 1 2 5 5 3 NaN 3 4 6 6 

How to do it?

I am sure this is a very simple question, but since I am new to Pandas any help would be appreciated!

+5
source share
3 answers

You can use where , which is the if / else vector:

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

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

+5
source
 df['c'] = df['b'].fillna(df['a']) 

So what .fillna will do is fill in 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 'a' values ​​in the Nan 'b' values ​​AND the final answer will be in 'c'

0
source

Source: https://habr.com/ru/post/1236879/


All Articles