我有两个数据帧,分别为df1和df2。
在一个数据框中,我有一个搜索值列表(实际上是Col1)
Col1 Col2
A1 val1, val2
B2 val4, val1
C3 val2, val5
我有另一个数据框,其中有项目列表
value items
val1 apples, oranges
val2 honey, mustard
val3 banana, milk
val4 biscuit
val5 chocolate
我想遍历第一个DF并尝试使用该val作为键来从第二个DF搜索项目
预期产量:
A1 apples, oranges, honey, mustard
B2 biscuit, appleas, oranges
C3 honey, mustard, chocolate
我能够将值添加到数据框并通过第一个DF进行迭代
for index, row in DF1:
#list to hold all the values
finalList = []
list = df1['col2'].split(',')
for i in list:
print(i)
我只需要帮助即可从第二个数据框中获取值。将不胜感激。谢谢。
想法是使用lambda函数split
并按字典查找:
d = df2.set_index('value')['items'].to_dict()
df1['Col2'] = df1['Col2'].apply(lambda x: ', '.join(d[y] for y in x.split(', ') if y in d))
print (df1)
Col1 Col2
0 A1 apples, oranges, honey, mustard
1 B2 biscuit, apples, oranges
2 C3 honey, mustard, chocolate
如果items
值中存在列表,则解决方案将通过展平进行更改:
d = df2.set_index('value')['items'].to_dict()
f = lambda x: ', '.join(z for y in x.split(', ') if y in d for z in d[y])
df1['Col2'] = df1['Col2'].apply(f)
print (df1)
Col1 Col2
0 A1 apples, oranges
1 B2 biscuit, apples, oranges
2 C3 honey, mustard, chocolate
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句