replace all floats in df with corresponding index name

Question:

I want to replace all values in my df that are float (excluding nans), with the name of the index of the corresponding row.

I have this:

index1                10.0                          190.6   
index2                17.9                          NaN   
index3                NaN                           8.0
index4                9.0                           70.0   

I want to have this:

index1                index1                        index1                
index2                index2                        NaN   
index3                NaN                           index3                
index4                index4                        index4                

Any ideas?

Asked By: Shuman_tov

||

Answers:

Technically, np.nan is also float. If you want to replace non-null values with the index values, you can use df.where:

output = df.where(df.isna(), df.index.tolist())

Output:

           1     2
0       
index1  index1  index1
index2  index2  NaN
index3  NaN index3
index4  index4  index4
Answered By: Nuri Taş

if you want to do it for all columns of your df:

for column in df.columns:

    df[column] = [e for e in df.index if df[column].notna]

If you want to do it for some columns, replace df.columns for a list with the columns you want to handle

Regards,

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.