You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

解决Pandas合并报错‘unhashable type: dict’的可行方案咨询

Fixing "unhashable type: dict" When Merging Pandas DataFrames

Hey there! Let's work through this merge issue step by step to get it sorted.

First, let's break down why you're seeing that error: Pandas requires merge keys to be hashable (think strings, numbers, or tuples) because it uses these keys to group and match rows. Dictionaries are mutable and unhashable, so using a dict column directly as the merge key will throw that unhashable type: dict error every time.

Why your initial string conversion didn't work

When you ran dk['result']= str(dk['result']), you weren't converting each dictionary in the column to a string—you were converting the entire Series object to a single long string. If you checked the values after that, you'd see something like:

"0    {'key': 'value1'}\n1    {'key': 'value2'}\nName: result, dtype: object"

That's just a text representation of the whole Series, not individual dictionary strings for each row. No wonder the merge failed!

Solution 1: Convert each dictionary to a standardized string

Instead of converting the whole Series, use apply() to turn each dictionary into a string. For better consistency (especially if dictionaries might have the same content but different key orders), use json.dumps() with sort_keys=True—this ensures identical dictionaries get identical string representations, even if their keys are ordered differently.

Here's the code:

import json
import pandas as pd

# Create consistent string columns from the dict columns
ds['result_key'] = ds['result'].apply(lambda x: json.dumps(x, sort_keys=True))
dk['result_key'] = dk['result'].apply(lambda x: json.dumps(x, sort_keys=True))

# Merge using the new string columns
result = pd.merge(ds, dk, on='result_key')

If you don't need to handle key order differences, you could also use str() directly in apply():

ds['result_key'] = ds['result'].apply(str)
dk['result_key'] = dk['result'].apply(str)

But json.dumps() is more reliable for matching truly identical dictionaries.

Solution 2: Extract a unique key from the dictionaries (better if possible)

If your dictionaries contain a unique identifier (like an id key that's consistent across both DataFrames), extracting that key is a cleaner and more efficient approach than string conversion. For example:

# Extract the unique key from each dictionary (adjust the key name to match your data)
ds['result_id'] = ds['result'].apply(lambda x: x.get('id'))
dk['result_id'] = dk['result'].apply(lambda x: x.get('id'))

# Merge using the extracted key
result = pd.merge(ds, dk, on='result_id')

This avoids any string-related mismatches and is faster for large datasets.

内容的提问来源于stack exchange,提问作者rahul knair

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 16:37:57