如果该列包含另一个数据框的列中的字符串,则在该数据框中创建一个新列 [英] Create a new column in a dataframe if the column contains a string from a column of another dataframe

查看:81
本文介绍了如果该列包含另一个数据框的列中的字符串,则在该数据框中创建一个新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果该列包含第二个数据框的列中的任何值,我想在数据框中创建一个新列.

I want to create a new column in my dataframe if the column contains any of the values from a column of a second dataframe.

第一个数据帧

WXYnineZAB
EFGsixHIJ
QRSeightTUV
GHItwoJKL
YZAfiveBCD
EFGsixHIJ
MNOthreePQR
ABConeDEF
MNOthreePQR
MNOthreePQR
YZAfiveBCD
WXYnineZAB
GHItwoJKL
KLMsevenNOP
EFGsixHIJ
ABConeDEF
KLMsevenNOP
QRSeightTUV
STUfourVWX
STUfourVWX
KLMsevenNOP
WXYnineZAB
CDEtenFGH
YZAfiveBCD
CDEtenFGH
QRSeightTUV
ABConeDEF
STUfourVWX
CDEtenFGH
GHItwoJKL

第二个数据框

one
three
five
seven
nine

输出数据框

WXYnineZAB,nine
EFGsixHIJ,***
QRSeightTUV,***
GHItwoJKL,***
YZAfiveBCD,five
EFGsixHIJ,***
MNOthreePQR,three
ABConeDEF,one
MNOthreePQR,three
MNOthreePQR,three
YZAfiveBCD,five
WXYnineZAB,nine
GHItwoJKL,***
KLMsevenNOP,seven
EFGsixHIJ,***
ABConeDEF,one
KLMsevenNOP,seven
QRSeightTUV,***
STUfourVWX,***
STUfourVWX,***
KLMsevenNOP,seven
WXYnineZAB,nine
CDEtenFGH,***
YZAfiveBCD,five
CDEtenFGH,***
QRSeightTUV,***
ABConeDEF,one
STUfourVWX,***
CDEtenFGH,***
GHItwoJKL,***

为了易于解释,我将第一个数据帧设置为3个字符+搜索字符串+ 3个字符,但是我的实际文件没有这样的一致性.

To explain it easily I made the first dataframe be 3chars + search string + 3chars, but my actual file doesn't have any consistency like this.

推荐答案

如果您想避免使用RegEx,这是一个纯粹基于列表的解决方案:

If you want to avoid RegEx, here is a purely list-based solution:

# Sample DataFrames (structure is borrowed from MaxU)
d1 = pd.DataFrame({'txt':['WXYnineZAB','EFGsixHIJ','QRSeightTUV','GHItwoJKL']})
d2 = pd.DataFrame({'word':['two','six']})
# Check if word exists in any txt (1-liner).
exists = [list(d2.word[[word in txt for word in d2.word]])[0] if sum([word in txt for word in d2.word]) == 1 else '***' for txt in d1.txt]
# Resulting output
res = pd.DataFrame(zip(d1.txt,exists), columns = ['text','word'])

结果:

          text word
0   WXYnineZAB  ***
1    EFGsixHIJ  six
2  QRSeightTUV  ***
3    GHItwoJKL  two

这篇关于如果该列包含另一个数据框的列中的字符串,则在该数据框中创建一个新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆