Fill values with data from other columns – Python

Question:

enter image description here

I have an Excel spreadsheet that I have already loaded into Jupyter.

I need to fill in the Nan values of the SPECIES column by the columns on the left side (GENERO, FAMILY, ORDER and etc. until DOMAIN), when I have Nan, I would like to fill in the column on the left, if the column on the left has nan I would like to fill in the column on the left, and so on.

In short, if you don’t have SPECIES, fill in SPECIES by GENERO, if GENERO is Nan, fill in SPECIES by FAMILY, if FAMILY is Nan, fill in SPECIES by ORDER and so on. In the end, I wanted another excel table to be generated with the same number of rows and columns as the one I’m working on.

I’ve tried:

temp = table['SPECIES'].mask(table['GENRE'].isna()).bfill() 
table['SPECIES'] = table['SPECIES'].fillna(temp) 
display (temp )

Answers:

Check below code

import pandas as pd
import numpy as np 

df = pd.DataFrame({"col1":[3,np.nan,np.nan],"col2":[np.nan,114,np.nan], "col3":[4,66,8]})

df['col4'] = np.nan

df['col4'] = df.col4.fillna(df.col1).fillna(df.col2).fillna(df.col3)

df

Output:

enter image description here

Answered By: Abhishek
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.