合并列表列失败 [英] Merge list column fail

查看:103
本文介绍了合并列表列失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:

df1 = pd.DataFrame({'a':list('ab'), 'b':[[1,2],[4,5]]})
print (df1)
   a       b
0  a  [1, 2]
1  b  [4, 5]

df2 = pd.DataFrame({'c':list('cd'), 'b':[[1,7],[4,5]]})
print (df2)
        b  c
0  [1, 7]  c
1  [4, 5]  d

我尝试按列blist s合并:

I try merge by column b with lists:

df = pd.merge(df1, df2, on='b')

TypeError:*之后的类型对象参数必须是序列,而不是映射

TypeError: type object argument after * must be a sequence, not map

我找到了将列转换为元组的解决方案:

I find solution with convert columns to tuples:

df1['b'] = df1['b'].apply(tuple)
df2['b'] = df2['b'].apply(tuple)

df = pd.merge(df1, df2, on='b')
print (df)
   a       b  c
0  b  (4, 5)  d

但是为什么具有list列的merge失败了?

But why merge with lists columns failed?

推荐答案

当我在python3.6中尝试您的示例时

When I try your example in python3.6

df1 = pd.DataFrame({'a':list('ab'), 'b':[[1,2],[4,5]]})
print (df1)

df2 = pd.DataFrame({'c':list('cd'), 'b':[[1,7],[4,5]]})
print (df2)

df = pd.merge(df1, df2, on='b')

我收到(最终)错误

TypeError: unhashable type: 'list'

由于要进行合并,因此要进行合并的列必须是可哈希的. 如果您尝试散列其中一个值,则会给出相同的错误

Because for merging, the column to merge on needs to be hashable. The same error is given, if you try to hash one of your values

hash([1,7])

将值转换为元组使其可散列

Converting the values to tuple makes them hashable

print(hash((1,7)))

1303117175

这就是为什么无法将列与列表合并.没有哈希值.

That's why mergeing column with lists is not possible. No hash.

这篇关于合并列表列失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆