Reputation: 15476
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.
Upvotes: 3
Views: 743
Reputation: 879661
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
.
Upvotes: 4