使用pandas melt函数报错‘unhashable type: Index’求解决方案
Hey there, let's break down why you're hitting this error and how to fix it quickly.
The Root Cause
Your code is passing pandas Index objects directly to the id_vars/value_vars parameters of melt(), and pandas doesn't handle that well. Specifically:
df_cns.columns[1:]returns an Index object (not a regular list of column names)- While
df_cns.columns[0]is a single column name string, mixing single values with Index objects can trigger unexpected type handling issues that lead to the "unhashable type: Index" error.
The Fix
Convert those Index references to regular Python lists, which melt() expects. Here are two clean ways to do this:
Option 1: Convert Index to list in-line
df_cns_depivot = pd.melt( df_cns, id_vars=[df_cns.columns[0]], # Wrap single column name in a list value_vars=df_cns.columns[1:].tolist(), # Convert Index to list with .tolist() value_name="Units" )
Option 2: Pre-convert all columns to a list first (more readable)
# First turn all column names into a regular list all_cols = df_cns.columns.tolist() # Now slice the list for melt() parameters df_cns_depivot = pd.melt( df_cns, id_vars=all_cols[0], value_vars=all_cols[1:], value_name="Units" )
Why This Works
Pandas' melt() function is designed to accept column names as strings, lists of strings, or other hashable iterables. By converting the Index object to a plain list, you're giving melt() exactly the input type it expects, eliminating the unhashable type error.
Wrapping the single id_vars column in a list is also a good practice—it makes your code more consistent and avoids edge cases where pandas might misinterpret a single column name as a non-iterable.
内容的提问来源于stack exchange,提问作者bhavesh

