Search code examples
pythonpandasnumpytranspose

Explode one row to multiple rows


I have a dataframe like this:

df:
    policy_num var_1  var_2  var3
    333           50    40     90
    222           20    10     15
    111           10    15     25

and I want it this way:

policy_num  var    value
333         var_1    50
333         var_2    40
333         var_3    90
222         var_1    20
222         var_2    10
222         var_3    15
111         var_1    10
111         var_2    15
111         var_3    25

doing df.T give something close but I don't know how to dill with the policy_num field as it represented by value of a column and not a key for the variables and values.


Solution

  • Try with melt

    out = df.melt(policy_num)