我有两本熊猫系列词典,如下所示:
series_1 = [{'id': 'testProd_1', 'q1':'Foo1', 'q2': 'Bar1'},
{'id': 'testProd_2', 'q1':'Foo2', 'q2': 'Bar2'},
{'id': 'testProd_3', 'q1':'Foo3', 'q2': 'Bar3'},
{'id': 'testProd_5', 'q1':'Foo5', 'q2': 'Bar5'}
]
series_2 = [{'q1':'Foo1', 'q2': 'Bar1'},
{'q1':'Foo2', 'q2': 'Bar2'},
{'q1':'Foo3', 'q2': 'Bar3'},
{'q1':'Foo4', 'q2': 'Bar4'},
{'q1':'Foo5', 'q2': 'Bar{5}'}]
我正在尝试比较两个pandas系列,并提供从系列1到所有匹配系列2的id
expected_result = [{'id': 'testProd_1', 'q1':'Foo1', 'q2': 'Bar1'},
{'id': 'testProd_2', 'q1':'Foo2', 'q2': 'Bar2'},
{'id': 'testProd_3', 'q1':'Foo3', 'q2': 'Bar3'},
{'id': 'testProd_5', 'q1':'Foo5', 'q2': 'Bar{5}'}]
Series equal不起作用,因为一个系列的每个dict都有一个额外的键值对(“id”)。我必须循环遍历每个条目吗?获得预期结果的最有效方法是什么
我正在处理两个大型数据集,其中我试图将id从一个系列链接到另一个系列。数据基本相同,但有时某些键值对中的值有一些错误字符(例如:{5},(5),{ex.5})
有什么建议吗
谢谢
您可以像这样使用熊猫:
输出:
使用有问题的新数据更新
熊猫将为1对多连接或多对多连接创建笛卡尔生产。因此,您将看到这些组合
输出:
无重复项
在没有重复项的情况下,您可以创建一个cumcount,以便在df2中将行1连接到行1,如下所示:
输出:
所以看起来您想要使用的是
merge
。据我所知,您希望在'q1'键上找到两个数据帧的内部连接。如果是这样,那么merge绝对是适合您的功能。它的使用方式如下:series_join = series_1.merge(series_2, on='q1')
这样,它将找到q1的交集,并只选择匹配的数据对。如果您确实想在
q1
和q2
上加入,您可以在此处传入一个数组(尽管这不会给出您想要的输出,因为Bar5
无法与Bar{5}
进行比较,不幸的是:series_join = series_1.merge(series_2, on=['q1', 'q2'])
至于清除数据中的错误值以便以这种方式进行比较,我建议首先执行一个清理步骤,因为主合并步骤没有太多关于如何比较数据值的自定义
输出将包括一组重复的列,但您可以忽略这些列:
这是一个repl运行的地方
编辑:保留重复项
merge的默认功能是,它将在两个表中保留所有重复的键。这里处理重复项的问题是pandas不知道哪一行是预期的查找行,因此它只需为每个组合创建一对。如以下示例所示(系列1、2,然后合并):
因此,没有简单的方法说“选择第二个表的第一行”,但您可以做的只是使用类似^{} 的函数预先删除第二个表中的重复项
感谢所有的反馈
我使用了上述答案的组合,得出了对我有效的解决方案
序列_2的q1和q2值太多,具有错误的字符(例如:“{'、“.”、“}”等),并且混合了大小写
我首先应用了apply来清除所有小写的值,并使用replace删除特殊字符
从那时起,我将其应用于我的2系列(假设我转换为数据帧)
现在,由于trueString是干净的(小写和所有特殊字符都已删除),因此我使用了Scott Boston和Daneolog在上述文章中建议的pandas merge
结果数据框显示基于相同trueString的所有匹配,对于不匹配的,它保持为空。这是因为我使用了左连接(您也可以使用右连接并切换两个输入帧),而不是内部连接,因为我希望查看所有series_2数据,而不管是否找到id
希望这有帮助
相关问题 更多 >
编程相关推荐