pandas melt
1. "unpivot" a dataframe to a pseudo-series
Today I had to convert something like below:
import pandas as pd df = pd.DataFrame({"col1": [1, 2, 3, 4], "col2": [10, 11, 12, 13]}) print(df)
col1 col2 0 1 10 1 2 11 2 3 12 3 4 13
into something like this
df = pd.DataFrame({"col": [1, 2, 3, 4, 10, 11, 12, 13]}) print(df)
col 0 1 1 2 2 3 3 4 4 10 5 11 6 12 7 13
The easiest way is to use pd.melt
. Here's how to achieve it.
import pandas as pd df = pd.DataFrame({"col1": [1, 2, 3, 4], "col2": [10, 11, 12, 13]}) print("Before: \n", df) df = df.reset_index() df = pd.melt(df, id_vars=["index"], value_vars=["col1", "col2"]) df = df.drop(columns=["index", "variable"]) print("After: \n", df)
Before: col1 col2 0 1 10 1 2 11 2 3 12 3 4 13 After: value 0 1 1 2 2 3 3 4 4 10 5 11 6 12 7 13