Home > Net >  Fill values with data from other columns - Python
Fill values with data from other columns - Python

Time:07-28

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 )

CodePudding user response:

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

  • Related