'Apply column name to row values unless nan or null

I'm attempting to add the column name of a dataframe to each row containing a non null value.

A sample data set I am working with is:

       ID     County Other Phone 2 Gender
0   10379    ELKHART           nan      M
1   10319  VAN BUREN  555-777-4444        
2   10321    ELKHART           nan       
3     nan    ELKHART           nan       
4   10352    ELKHART  555-999-6666      M

Is there a way that I can get the dataframe to look something like below where the column name is added to the beginning of the value separating it with a :

          ID             County                Other Phone 2     Gender
0  ID: 10379    County: ELKHART                          nan  Gender: M
1  ID: 10319                     Other Phone 2: 555-777-4444    
2  ID: 10321    County: ELKHART                          nan     
3        nan    County: ELKHART                          nan   
4  ID: 10352    County: ELKHART  Other Phone 2: 555-999-6666  Gender: M


Solution 1:[1]

You can try apply on columns

df = df.apply(lambda col: col.mask(col.notna(), col.name+': '+col.astype(str)))

or with df.mask

m = df.notna()
df = df.mask(m, df.columns + ': ' + df.astype(str))
print(df)

            ID             County                Other Phone 2     Gender
0  ID: 10379.0    County: ELKHART                          NaN  Gender: M
1  ID: 10319.0  County: VAN BUREN  Other Phone 2: 555-777-4444       None
2  ID: 10321.0    County: ELKHART                          NaN       None
3          NaN    County: ELKHART                          NaN       None
4  ID: 10352.0    County: ELKHART  Other Phone 2: 555-999-6666  Gender: M

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1