Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas & python: unstack or pivot with many columns as indices?

Tags:

python

pandas

I have a dataframe like the following:

    A     B    C   Property   Value
1   Bob  b100  X1  prop1      a
2   Bob  b100  X1  prop2      b
3   Bob  b100  X2  prop1      c
4   Bob  b100  Y1  prop1      a
5   Bob  b100  Z   prop9      b
6   Bob  b200  X1  prop1      c
7   Bob  b200  X1  prop2      d

How can I use unstack, pivot, or some other method to only unstack the Property and Value columns?

I am trying to obtain the following dataframe:

    A     B    C   prop1  prop2   prop9
1   Bob  b100  X1  a        b       -
2   Bob  b100  X2  c        -       -
3   Bob  b100  Y1  a        a       -
4   Bob  b100  Z   -        -       b
5   Bob  b200  X1  c        d       -
like image 209
bwrabbit Avatar asked Jun 03 '26 22:06

bwrabbit


1 Answers

In [115]: (df.pivot_table(index=['A','B','C'], columns='Property', values='Value',
     ...:                 aggfunc='first', fill_value='-')
     ...:    .reset_index()
     ...:    .rename_axis(None,1))
     ...:
Out[115]:
     A     B   C prop1 prop2 prop9
0  Bob  b100  X1     a     b     -
1  Bob  b100  X2     c     -     -
2  Bob  b100  Y1     a     -     -
3  Bob  b100   Z     -     -     b
4  Bob  b200  X1     c     d     -

or using unstack:

In [124]: (df.set_index(['A','B','C','Property'])
     ...:    ['Value'].unstack('Property', fill_value='-')
     ...:    .reset_index()
     ...:    .rename_axis(None,1))
     ...:
Out[124]:
     A     B   C prop1 prop2 prop9
0  Bob  b100  X1     a     b     -
1  Bob  b100  X2     c     -     -
2  Bob  b100  Y1     a     -     -
3  Bob  b100   Z     -     -     b
4  Bob  b200  X1     c     d     -
like image 120
MaxU - stop WAR against UA Avatar answered Jun 06 '26 11:06

MaxU - stop WAR against UA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!