添加包含两个数据框之间匹配值列表的新列

Add new column with a list of the matching values between two dataframes

我有 2 个具有以下结构的数据帧:

DF1

ItemID     Item
Id1        Item1
Id2        Item2
Id3        Item3
...        ...
1000       Item1000

DF2

Index     ListOfItems
0         [Item1]
1         [Item1, Item3, Item5]
2         [Item2, Item3]
...       ...
N         [NItems]

这将是我的预期输出:

Index     ListOfItems               ListOfIds
0         [Item1]                   [Id1]
1         [Item1, Item3, Item5]     [Id1, Id3, Id5]
2         [Item2, Item3]            [Id2, Id3]
...       ...                       ...
N         [NItems]                  [NIds] 

将第二个 Dataframe 的 ListOfItmes 与第一个 Dataframe 的 ID 进行匹配,并在新列中创建 ID 列表

这是在不断变化的大型数据帧上完成的,因此性能很重要。我尝试了一些方法,但性能很差。

尝试:

df2['ListOfIds'] = df2['ListOfItems'].apply(lambda x: df1[df1['Item'].isin(x)].index.to_list())

示例数据:

>>> df1
         Item
ItemID       
Id1     Item1
Id2     Item2
Id3     Item3

>>> df2
                 ListOfItems
Index                       
0                    [Item1]
1      [Item1, Item3, Item5]
2             [Item2, Item3]

输出:

                 ListOfItems   ListOfIds
Index                                   
0                    [Item1]       [Id1]
1      [Item1, Item3, Item5]  [Id1, Id3]
2             [Item2, Item3]  [Id2, Id3]

上面的解决方案希望您将 ListOfItems 列中的值设为列表而不是字符串,如果不是列表,您可以执行以下操作将其从字符串转换为列表:

df2['ListOfItems'] = df2['ListOfItems'].str[1:-1].str.split(',').apply(lambda x: [i.strip() for  i in x])

df2=df2.replace(regex={'\[':'','\]':''})#去掉角括号

#in df2 使 ListOfItems 成为列表并展开,创建名为

的新列
ListOfIds and map over the ids
df2=df2.assign(ListOfItems=df2['ListOfItems'].str.split(',')).explode('ListOfItems').assign(ListOfIds=df2['ListOfItems'].map(dict(zip(df1['Item'], df1['ItemID']))))

#Groupby索引和年龄列表

df2.groupby('Index').agg(list)