0

I have a dataframe:

df = pd.DataFrame([
    {"node":"A","month":1,"val":-77},
    {"node":"A","month":2,"val":0},
    {"node":"B","month":1,"val":-16},
    {"node":"B","month":2,"val":0}
])

I'd like to modify this so that each month is within the same row and the month value is the key to the value of 'val':

df = pd.DataFrame([
    {"node":"A", 1: -77, 2: 0},
    {"node":"B", 1: -16, 2: 0}
])
Evan Brittain
  • 547
  • 5
  • 15

1 Answers1

0

Try with pandas.pivot_table():

import pandas as pd

df = pd.DataFrame([
    {"node":"A","month":1,"val":-77},
    {"node":"A","month":2,"val":0},
    {"node":"B","month":1,"val":-16},
    {"node":"B","month":2,"val":0}
])

df=df.pivot_table(index="node", columns="month", values="val").reset_index()

Output:

month node   1  2
0        A -77  0
1        B -16  0
Grzegorz Skibinski
  • 12,624
  • 2
  • 11
  • 34