Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas Use Value if Not Null, Else Use Value From Next Column

Given the following dataframe:

import pandas as pd df = pd.DataFrame({'COL1': ['A', np.nan,'A'],                     'COL2' : [np.nan,'A','A']}) df     COL1    COL2 0    A      NaN 1    NaN    A 2    A      A 

I would like to create a column ('COL3') that uses the value from COL1 per row unless that value is null (or NaN). If the value is null (or NaN), I'd like for it to use the value from COL2.

The desired result is:

    COL1    COL2   COL3 0    A      NaN    A 1    NaN    A      A 2    A      A      A 

Thanks in advance!

like image 826
Dance Party Avatar asked Feb 21 '16 00:02

Dance Party


People also ask

How do I specify NOT null in pandas?

mode. use_inf_as_na = True). Returns : Mask of bool values for each element in DataFrame that indicates whether an element is not an NA value. Example #1: Use notnull() function to find all the non-missing value in the dataframe.

How get value from another column in pandas?

You can extract a column of pandas DataFrame based on another value by using the DataFrame. query() method. The query() is used to query the columns of a DataFrame with a boolean expression.


1 Answers

In [8]: df Out[8]:   COL1 COL2 0    A  NaN 1  NaN    B 2    A    B  In [9]: df["COL3"] = df["COL1"].fillna(df["COL2"])  In [10]: df Out[10]:   COL1 COL2 COL3 0    A  NaN    A 1  NaN    B    B 2    A    B    A 
like image 189
Randy Avatar answered Sep 21 '22 22:09

Randy