Home > Software design >  replace all floats in df with corresponding index name
replace all floats in df with corresponding index name

Time:11-20

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?

CodePudding user response:

use:

df2=df.T
'''
        index1  index2  index3  index4
col1    10.0    17.9    nan     9.0
col2    190.6           8.0     70.0

'''
df2=df2.replace(np.nan,'nan') #Since nan values ​​are float type, I convert them to string nan.

for i in df2.columns:
        df2[i]=df2[i].apply(lambda x: i if isinstance(x, float) else x)

df2=df2.T.replace('nan',np.nan) #convert string nans to real nans
print(df2)
'''
index1  index1  index1
index2  index2     NaN
index3     NaN  index3
index4  index4  index4
'''

CodePudding user response:

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
  • Related