0

I have a pandas data frame with columns for a collection of locations, i.e. "station 1", "station 2", etc., for which each entry is a demand data value. It looks like this:

index  station 1  station 2
0        0.1         1.2
1       -0.04        0.9

I'd like to create a new dataframe with columns "station" that has station entries and "demand' that has the corresponding data value. Like this

index station    demand
0     station 1  0.1
1     station 1  -0.4 
2     station 2  1.2
3     station 2  0.9

How can I do this using pandas built-in dataframe manipulation?

I've tried using the melt and wide_to_long functions, but I don't really think these are what I need

  • 1
    check out `melt()` https://stackoverflow.com/questions/68961796/how-do-i-melt-a-pandas-dataframe – JonSG Mar 20 '23 at 20:01
  • 1
    "I've tried using the melt and wide_to_long functions..." what _specifically_ have you tried, and what was wrong with the output? – G. Anderson Mar 20 '23 at 20:08

1 Answers1

0

using melt():

df = df.drop('index', axis=1).melt(var_name='station', value_name='demand')
df.insert(0, 'index', value=df.index)

out

omer
  • 522
  • 1
  • 8
  • 26