Simultaneously melt multiple columns with pandas

hello Community,
am trying to melt multiple columns but am getting an error

import streamlit as st
import pandas as pd

df = pd.DataFrame({'City': ['Houston', 'Austin', 'Hoover'],
	'State': ['Texas', 'Texas', 'Alabama'],
	'Name':['Aria', 'Penelope', 'Niko'],
	'Mango':[4, 10, 90],
	'Orange': [10, 8, 14], 
	'Watermelon':[40, 99, 43],
	'Gin':[16, 200, 34],
	'Vodka':[20, 33, 18]},
	columns=['City', 'State', 'Name', 'Mango', 'Orange', 'Watermelon', 'Gin', 'Vodka'])

st.write(df)
City    State      Name  Mango  Orange  Watermelon  Gin  Vodka
0  Houston    Texas      Aria      4      10          40   16     20
1   Austin    Texas  Penelope     10       8          99  200     33
2   Hoover  Alabama      Niko     90      14          43   34     18

new_df = df.melt(id_vars=['City', 'State'], value_vars=[['Mango', 'Orange', 'Watermelon'], ['Gin', 'Vodka']],
	var_name=['Fruit', 'Drink'], value_name=['Pounds', 'Ounces'])

st.write(new_df) 

when i execute this line of code i get TypeError: unhashable type: 'list’

Hey @wilson_uzziel,

Did not test your code to be sure but pandas melt does not accept a list of list in value_vars so it won’t accept [['Mango', 'Orange', 'Watermelon'], ['Gin', 'Vodka']] as input, so it’s probably bumping on your ['Mango', 'Orange', 'Watermelon'] and returning unhashable type: list.

You’re better off concatenating 2 separate melts instead, like in this SO answer

2 Likes

Thanks alot @andfanilo. It worked fine