如何根据特定的键值对比较两个Pandas系列?

2024-10-01 00:22:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两本熊猫系列词典,如下所示:

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})

有什么建议吗

谢谢


Tags: 数据idbar键值seriesq2q1foo1
3条回答

您可以像这样使用熊猫:

pd.DataFrame(series_1)[['id','q1']].merge(pd.DataFrame(series_2), on=['q1']).to_dict('records')

输出:

[{'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}'}]

使用有问题的新数据更新

熊猫将为1对多连接或多对多连接创建笛卡尔生产。因此,您将看到这些组合

df1.merge(df2, on=['q1'])

输出:

           id    q1  q2_x    q2_y
0  testProd_1  Foo1  Bar1    Bar1
1  testProd_2  Foo2  Bar2    Bar2
2  testProd_3  Foo3  Bar3    Bar3
3  testProd_5  Foo5  Bar5  Bar{5}
4  testProd_5  Foo5  Bar5  Bar{6}
5  testProd_6  Foo5  Bar6  Bar{5}
6  testProd_6  Foo5  Bar6  Bar{6}

无重复项

在没有重复项的情况下,您可以创建一个cumcount,以便在df2中将行1连接到行1,如下所示:

df1m = df1.assign(mergekey=df1.groupby('q1').cumcount())
df2m = df2.assign(mergekey=df2.groupby('q1').cumcount())
df1m.merge(df2m, on=['q1','mergekey'])

输出:

           id    q1  q2_x  mergekey    q2_y
0  testProd_1  Foo1  Bar1         0    Bar1
1  testProd_2  Foo2  Bar2         0    Bar2
2  testProd_3  Foo3  Bar3         0    Bar3
3  testProd_5  Foo5  Bar5         0  Bar{5}
4  testProd_6  Foo5  Bar6         1  Bar{6}

所以看起来您想要使用的是merge。据我所知,您希望在'q1'键上找到两个数据帧的内部连接。如果是这样,那么merge绝对是适合您的功能。它的使用方式如下:

series_join = series_1.merge(series_2, on='q1')

这样,它将找到q1的交集,并只选择匹配的数据对。如果您确实想在q1q2上加入,您可以在此处传入一个数组(尽管这不会给出您想要的输出,因为Bar5无法与Bar{5}进行比较,不幸的是:

series_join = series_1.merge(series_2, on=['q1', 'q2'])

至于清除数据中的错误值以便以这种方式进行比较,我建议首先执行一个清理步骤,因为主合并步骤没有太多关于如何比较数据值的自定义

输出将包括一组重复的列,但您可以忽略这些列:

           id    q1  q2_x    q2_y
0  testProd_1  Foo1  Bar1    Bar1
1  testProd_2  Foo2  Bar2    Bar2
2  testProd_3  Foo3  Bar3    Bar3
3  testProd_5  Foo5  Bar5  Bar{5}

这是一个repl运行的地方

编辑:保留重复项

merge的默认功能是,它将在两个表中保留所有重复的键。这里处理重复项的问题是pandas不知道哪一行是预期的查找行,因此它只需为每个组合创建一对。如以下示例所示(系列1、2,然后合并):

           id    q1    q2
0  testProd_1  Foo1  Bar1
1  testProd_2  Foo2  Bar2
2  testProd_3  Foo3  Bar3
3  testProd_5  Foo5  Bar5
4  testProd_6  Foo5  Bar6
     q1      q2
0  Foo1    Bar1
1  Foo2    Bar2
2  Foo3    Bar3
3  Foo4    Bar4
4  Foo5  Bar{5}
5  Foo5  Bar{6}
           id    q1    q2_y
0  testProd_1  Foo1    Bar1
1  testProd_2  Foo2    Bar2
2  testProd_3  Foo3    Bar3
3  testProd_5  Foo5  Bar{5} <<< [3  testProd_5  Foo5  Bar5] + [4  Foo5  Bar{5}]
4  testProd_5  Foo5  Bar{6} <<< [3  testProd_5  Foo5  Bar5] + [5  Foo5  Bar{6}]
5  testProd_6  Foo5  Bar{5} <<< [4  testProd_6  Foo5  Bar6] + [4  Foo5  Bar{5}]
6  testProd_6  Foo5  Bar{6} <<< [4  testProd_6  Foo5  Bar6] + [5  Foo5  Bar{6}]

因此,没有简单的方法说“选择第二个表的第一行”,但您可以做的只是使用类似^{}的函数预先删除第二个表中的重复项

感谢所有的反馈

我使用了上述答案的组合,得出了对我有效的解决方案

序列_2的q1和q2值太多,具有错误的字符(例如:“{'、“.”、“}”等),并且混合了大小写

我首先应用了apply来清除所有小写的值,并使用replace删除特殊字符

# Creates a uniform value string 
def getTrueString(valString):
    
    trueString= valString.lower()
    remove_specialChrs = [' ','{','}','ex.']
    
    for char in remove_specialChrs:
        trueString= trueString.replace(char,'')
            
    return trueString.strip()

从那时起,我将其应用于我的2系列(假设我转换为数据帧)

series_1['trueString'] = series_1['valString'].apply(getTrueString)
series_2['trueString'] = series_2['valString'].apply(getTrueString)

现在,由于trueString是干净的(小写和所有特殊字符都已删除),因此我使用了Scott Boston和Daneolog在上述文章中建议的pandas merge

joined_data = pd.merge(series_2, series_1, on='trueString', how='left' )

结果数据框显示基于相同trueString的所有匹配,对于不匹配的,它保持为空。这是因为我使用了左连接(您也可以使用右连接并切换两个输入帧),而不是内部连接,因为我希望查看所有series_2数据,而不管是否找到id

希望这有帮助

相关问题 更多 >