GinjaNinja
GinjaNinja

Reputation: 806

Different Views on Same Dataframe

I have a dataframe that resembles the below:

Date Symbol High Med Low Comment
01-Jan-2021 A 0.3 0.2 0.1 Comment on A
01-Jan-2021 B 3 2 1 Comment on B

As you can see above, the comment applies to all prices (high, medium and low)

I now need to turn this into a melted dataframe without the comment, which I achieve as below:

df = df.melt(id_vars=['Date', 'Symbol'], value_vars=['High', 'Medium', 'Low'], var_name='Quote', value_name = 'Metric')

Giving:

Date Symbol Quote Metric
01-jan-21 A High 0.3
01-jan-21 A Med 0.2
01-jan-21 A Low 0.1
01-jan-21 B High 0.3
01-jan-21 B Med 0.2
01-jan-21 B Low 0.1

Where I'm struggling is I now want to apply the comment to each of the lines in the above melted view, giving:

Date Symbol Quote Comment
01-jan-21 A High Comment on A
01-jan-21 A Med Comment on A
01-jan-21 A Low Comment on A
01-jan-21 B High Comment on B
01-jan-21 B Med Comment on B
01-jan-21 B Low Comment on B

Note how the single comment for each symbol is now repeated for each Quote. This is example only, there are a wider range of dates and quotes (i.e. several dates for each quote and more than just quotes A and B)

Any help appreciated.

Upvotes: 1

Views: 35

Answers (1)

jezrael
jezrael

Reputation: 863226

So need add Comment to id_vars parameter?

df = df.melt(id_vars=['Date', 'Symbol','Comment'], 
             value_vars=['High', 'Medium', 'Low'], 
             var_name='Quote', 
             value_name = 'Metric')

Also if alla nother columns not defined in id_vars are used in value_vars is possible use:

df = df.melt(id_vars=['Date', 'Symbol','Comment'], 
             var_name='Quote', 
             value_name = 'Metric')

Upvotes: 1

Related Questions