【发布时间】:2021-11-02 02:21:33
【问题描述】:
我想将一个函数应用于 pandas 数据框的两列(A 和 B),以测试它们的每个值是否与字典中的相同结果匹配。我希望它将结果返回到第三列。
我已经尝试了下面的代码和关闭变体,但我不断收到错误,我认为我对数据结构有一些基本的不了解。谁能解释我哪里出错了?我可以想象一些繁琐的替代方法来做到这一点,但我确信一定有一个优雅的解决方案。
def do_they_match(A1,A2):
if A1 in dictionary and A2 in dictionary and dictionary[A1] == dictionary[A2]:
return 1
else:
return 0
df['match'] = df.apply(lambda x: do_they_match(x['A'],x['B']))
## also tried ##
df = df.assign(link=lambda x: do_they_match(x['A'],x['B']))
对于上下文,对于最后一行的替代代码,我得到的错误是 IndexError: ('A', 'occurred at index A') 或 TypeError: 'Series' objects are mutable, thus they cannot be hashed。数据框列和字典中的值都是字符串。
感谢您的帮助!
【问题讨论】:
-
你的意思是
df['match'] = df.apply(lambda x: do_they_match(x['A'], x['B']), axis=1)吗?
标签: python pandas dictionary mapping apply