Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pandas: how do I fill none empty rows with its corresponding column names?

Tags:

python

pandas

Here's the original df:

A   B   C 
32      4
    2   
2       
9       2
2   6   

I want to fill in cells that have data with the column names.The output will look like this:

A   B   C 
A       C 
    B   
A       
A       C 
A   B   

Thanks RJ

like image 872
Rey John Estera Avatar asked Dec 10 '25 17:12

Rey John Estera


2 Answers

Another way is np.where and would be very fast as well:

out = df.copy()
out[:] = np.where(df.notna(),df.columns,np.nan)

print(out)

     A    B    C
0    A  NaN    C
1  NaN    B  NaN
2    A  NaN  NaN
3    A  NaN    C
4    A    B  NaN
like image 83
anky Avatar answered Dec 13 '25 06:12

anky


We could do stack and unstack

s=df.stack()
s[:]=s.index.get_level_values(1)
s=s.unstack()
s
Out[496]: 
     A    B    C
0    A  NaN    C
1  NaN    B  NaN
2    A  NaN  NaN
3    A  NaN    C
4    A    B  NaN
like image 42
BENY Avatar answered Dec 13 '25 07:12

BENY



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!