ajwood ajwood - 2 months ago 5
Python Question

Creating new columns from unique values across rows in pandas

I'm trying to use unique values in a pandas column to generate a new set of column. Here's an example

DataFrame
:

meas1 meas2 side newindex
0 1 3 L 0
1 2 4 R 0
2 6 8 L 1
3 7 9 R 1


I'd like to "multiply" my measurement columns with my key columns to generate a
DafaFrame
that looks like this:

meas1_L meas1_R meas2_L meas2_R
0 1 2 3 4
1 6 7 8 9


Note it's essentially the inverse of this question.

Answer

Use DataFrame.pivot:

# Perform the pivot.
df = df.pivot(index='newindex', columns='side').rename_axis(None)

# Format the columns.
df.columns = df.columns.map('_'.join)

The resulting output:

   meas1_L  meas1_R  meas2_L  meas2_R
0        1        2        3        4
1        6        7        8        9
Comments