Home > Blockchain >  Pandas merge multiple value columns into a value and type column
Pandas merge multiple value columns into a value and type column

Time:01-29

I have a pandas dataframe where there are multiple integer value columns denoting a count. I want to transform this dataframe such that the value columns are merged into one column but another column is created denoting the column the value was taken from.

Input

    a   b   c
0   2   5   8
1   3   6   9
2   4   7   10

Output

    count   type
0   2       a
1   3       a
2   4       a
3   5       b
4   6       b
5   7       b
6   8       c
7   9       c
8   10      c

Im sure this is possible by looping over the entries and creating however many rows for each original row but im sure there is a pandas way to achieve this and I would like to know what it is called.

CodePudding user response:

You could do that with the following

pd.melt(df, value_vars=['a','b','c'], value_name='count', var_name='type')

  •  Tags:  
  • Related