Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Row and column indexes of True values

I have an NxN pandas DataFrame which contains booleans. For example:

In[56]: df
Out[56]: 
       15     25     35     45     55
10   True  False  False  False  False
20  False   True  False  False  False
30  False  False   True  False  False
40  False  False  False   True  False
50  False  False  False  False   True

What I need to do is collapse this frame into an Nx2 pandas DataFrame which has the index and column values that have True at the intersection as the record values. For example:

In[62]: res
Out[62]: 
    0   1
0  10  15
1  20  25
2  30  35
3  40  45
4  50  55

Can't seem to find a simple way to do this.

like image 873
Jason Strimpel Avatar asked Jan 18 '26 03:01

Jason Strimpel


1 Answers

pd.melt "unpivots" a DataFrame from wide to long format:

result = pd.melt(df.reset_index(), id_vars=['index'])
mask = result['value'] == True
result = result.loc[mask, ['index', 'variable']]
result.columns = [0, 1]
print(result)

yields

     0   1
0   10  15
6   20  25
12  30  35
18  40  45
24  50  55

PS. Your desired DataFrame has two columns which have values which act as coordinates. The df.pivot method converts DataFrames with coordinate-like columns into "wide-format" DataFrames like your original DataFrame. When you want to go the other way, use pd.melt.

like image 167
unutbu Avatar answered Jan 19 '26 15:01

unutbu



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!