'How do I do this transformation in pandas?

I forgot what it is called, but I need to do the following transformation in Pandas:

I have:

[Name, address, phone, IDnum]
[John, Doe lane, xxxx, A111]

and I want:

[Name, data_type, value] 
[John, address, doe lane]
[John, phone, xxxx]
[John, IDnum, A111]

I know there is an easy way to do this, I just forgot.



Solution 1:[1]

I believe you are looking for pandas.melt

# Create the dataframe
df=pd.DataFrame(data=
    {
        'Name': ['John'], 
        'address': ['Doe lane'],
        'phone': ['xxxx'],
        'IDnum': ['A111'],
     })
df

# Apply melt
pd.melt(df, id_vars=['Name'], ignore_index=True)

# Result
Index Name variable value
0 John address doe lane
1 John phone xxxx
2 John IDnum A111

You can also set the dataframe equal to the result if you need to call it again

df_melted = pd.melt(df, id_vars=['Name'], ignore_index=True)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dharman