While working over dataframes, we might be have various columns of same or different values. Now we are interested to keep all numbers in single column and rest column should act as id variables. This can easily be done by melt function.
So this recipe is a short example on What does a melt function do on a dataframe. Let's get started.
import pandas as pd import seaborn as sb
Let's pause and look at these imports. Pandas is generally used for performing mathematical operation and preferably over arrays. Seaborn will help us in importing dataset.
df = sb.load_dataset('tips') print(df.head())
Here we have imported datset from seaborn library.
Now, our dataset is ready.
df_melt=pd.melt(df, id_vars =['sex','smoker','day','time'], value_vars =['total_bill','tip','size']) print(df_melt.head())
As you can see, all id variables are kept in different columns and value variables will be melted.
Once we run the above code snippet, we will see:
Scroll down the ipython file to visualize the final output.
Melting can easily be observed.