我有两个不能在任何值上联接的数据帧,但是第一个数据帧(dfA
)中有一列值可能与第二个数据帧(dfB
)的多个列中的值匹配,也可能不匹配。“text\u bod”列的值特别大,平均字符串长度约为1500个字符。你知道吗
dfB
中的value1
列和value2
列并不总是记录值,即使存在值,但如果存在值,则几乎总是在text_bod
列的文本中的某个地方找到。我试图弄清楚dfA
中的值是否存在于dfB
。你知道吗
如果dfA
中的值存在于dfB
中,我想将dfA
中的一些信息附加到找到该值的dataframe中的新列中。例如,我想在dfB
中添加一个'name'、'color'和'animal'列,然后为找到的值附加相应的名称、颜色和动物。你知道吗
到目前为止,我得出的结论是:
def extract(t):
s = ('|').join(dfA['value'])
return re.search(s, t)
tqdm.pandas()
dfB['value'] = dfB['text_bod'].progress_map(extract)
我很想听听关于如何1)优化此搜索和2)将与值对应的信息附加到dfB
中的新列的任何建议。你知道吗
dfA
(~200000行)
value name color animal
0 es9bum name1 red dolphin
1 qgl8 name2 cerulean mountaingoat
2 klkwv name3 platinum mantisshrimp
3 tokgs name4 fuchsia tarantula
4 cnwsaq5 name5 frost gentoopenguin
dfB
(~1500000行)
value1 value2 text_bod
0 null tokgs here are some tokgs
1 null null something es9bum
2 klkwv null blahblahblahklkwv
3 null null boop: qgl8. more&&
4 null null hi it me
5 null null here are more words
6 y2kbc null words and stuff
7 null null so much text
8 null null have a nice cnwsaq5
9 null null null
这是我想要输出的:
dfB
(~1500000行)
value1 value2 text_bod name color animal
0 null tokgs here are some tokgs name4 fuchsia tarantula
1 null null something es9bum name1 red dolphin
2 klkwv null blahblahblahklkwv name3 platinum mantisshrimp
3 null null boop: qgl8. more&& name2 cerulean mountaingoat
4 null null hi it me NaN NaN NaN
5 null null here are more words NaN NaN NaN
6 y2kbc null words and stuff name99 onyx direwolf
7 null null so much text NaN NaN NaN
8 null null have a nice cnwsaq5 name5 frost gentoopenguin
9 null null null NaN NaN NaN
我们可以使用^{} 在
text_bod
列中查找单词并提取它们。之后,我们使用这些提取的单词作为key
到merge
df1
和dfA
来获得想要的列。你知道吗如果您使用的是Python 3.6或更高版本
我们可以在第三行中使用
f-strings
,这使我们的代码更加简洁:相关问题 更多 >
编程相关推荐