Dataframe melt and retain index

Viewed 58

I have a dataframe like so:

    df = pd.DataFrame(
        [
            ["True", "False"],
            ["True", "True"],
            ["False", "True"],

        ],
        index=["bob", "sue", "joe"],
        columns=["R1", "R2"],
    )

I'd like to melt the df so that the index names are used, and replace the Trues with the column name, so the output is like so:

    df = pd.DataFrame(
        [
            ["bob", "R1"],
            ["sue", "R1"],
            ["sue", "R2"],
            ["joe", "R2"],
        ],
        columns=["Names", "Role"],
    )

How can I achieve this?

1 Answers

Use DataFrame.melt with convert index to column first:

df = df.rename_axis('Names').reset_index().melt('Names', var_name='Role')

And then filter by True value:

df = df.loc[df['value'].map({'True':True, 'False':False}), ['Names','Role']]

Or:

df = df.loc[df['value'] == 'True', ['Names','Role']]

print(df)  
  Names Role
0   bob   R1
1   sue   R1
4   sue   R2
5   joe   R2
Related