1

I have following dataframe df:

data = {'SAP ID': ['MATSAP1', 'MATSAP2'],
    'DESCRIPTION': ['DESC1', 'DESC2'],
    'BASIC': ['BD1', 'BD2'],
    'LINK': ['MD1', 'MD2']}

df = pd.DataFrame(data)

I want to melt the df and have the following output: enter image description here

However, on using the below code, getting ouput:

df_melted = pd.melt(df,id_vars=['SAP ID'], value_vars=df.columns.tolist())

Output: enter image description here

Is there anyway through which this can be achieved?

Anoushiravan R
  • 21,622
  • 3
  • 18
  • 41
  • 1
    If you provide python code for your example data (instead of screenshots or simple description), it's easier for people to reproduce your problem and you are more likely to get a useful answer – slymore Sep 10 '22 at 10:56
  • Added the code with the data as well. – Deluxplanet345 Sep 10 '22 at 11:12

1 Answers1

1

There might be more elegant solution but if you just copy your column to appear twice and the melt the data, you get your desired output:

df['SAP ID copy'] = df['SAP ID']

out = df.melt('SAP ID copy').rename(columns={'SAP ID copy': 'SAP ID'})
print(out)
    SAP ID     variable    value
0  MATSAP1       SAP ID  MATSAP1
1  MATSAP2       SAP ID  MATSAP2
2  MATSAP1  DESCRIPTION    DESC1
3  MATSAP2  DESCRIPTION    DESC2
4  MATSAP1        BASIC      BD1
5  MATSAP2        BASIC      BD2
6  MATSAP1         LINK      MD1
7  MATSAP2         LINK      MD2

OR

df = df.set_index('SAP ID',drop=False).stack().reset_index()
df.columns = ['SAP ID', 'variable', 'value']
out = df.sort_values('variable').reset_index(drop=True)
print(out)
    SAP ID     variable    value
0  MATSAP1        BASIC      BD1
1  MATSAP2        BASIC      BD2
2  MATSAP1  DESCRIPTION    DESC1
3  MATSAP2  DESCRIPTION    DESC2
4  MATSAP1         LINK      MD1
5  MATSAP2         LINK      MD2
6  MATSAP1       SAP ID  MATSAP1
7  MATSAP2       SAP ID  MATSAP2
Rabinzel
  • 7,757
  • 3
  • 10
  • 30