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!
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With