I am trying to stack this table based on ID column but only considering columns [A-D] where the value is 1 and not 0.
Current df:
| ID | A | B | C | D |
|---|---|---|---|---|
| 1 | 1 | 0 | 0 | 1 |
| 3 | 0 | 1 | 0 | 1 |
| 7 | 1 | 0 | 1 | 1 |
| 8 | 1 | 0 | 0 | 0 |
What I want:
| ID | LETTER |
|---|---|
| 1 | A |
| 1 | D |
| 3 | B |
| 3 | D |
| 7 | A |
| 7 | C |
| 7 | D |
| 8 | A |
The following code works but I need a more efficient solution as I have a df with 93434 rows x 12377 columns.
stacked_df = df.set_index('ID').stack().reset_index(name='has_letter').rename(columns={'level_1':'LETTER'})
stacked_df = stacked_df[stacked_df['has_letter']==1].reset_index(drop=True)
stacked_df.drop(['has_letter'], axis=1, inplace=True)