0

Here is what my data frame looks like

id name val weight
1  x    10  0.3
1  y    5   0.1
1  z    6   -0.7
1  q    7   -0.3
2  t    3   0.5
2  m    2   0.1
2  s    8   -0.8
2  b    9   -0.2

And here is how I would like to look:

id name_pos val_pos weight_pos name_neg val_neg weight_neg
1  x        10      0.3        z        6       -0.7
1  y        5       0.1        q        7       -0.3
2  t        3       0.5        s        8       -0.8
2  m        2       0.1        b        9       -0.2

I can't think of an elegant solution for completing this. My only thoughts are brute force methods.

Any help would be much appreciated.

madsthaks
  • 377
  • 1
  • 6
  • 16
  • Does each `id` have exactly `4` rows? What happens if they don't? – Quang Hoang Dec 30 '19 at 18:36
  • Yes, they will always have a set number of rows. – madsthaks Dec 30 '19 at 18:37
  • Does this answer your question? [pandas create new column based on values from other columns / apply a function of multiple columns, row-wise](https://stackoverflow.com/questions/26886653/pandas-create-new-column-based-on-values-from-other-columns-apply-a-function-o) – Lucas Maraal Dec 30 '19 at 18:46

1 Answers1

1

Here's a solution that worked:

df.set_index(['id'], inplace = True)

pd.concat((df[df.weight.gt(0)].add_suffix('_pos'),
           df[df.weight.lt(0)].add_suffix('_neg')),
          axis=1)
madsthaks
  • 377
  • 1
  • 6
  • 16