基于逗号拆分元素是否是Python中另一列的子字符串合并两个数据帧
给定数据帧基于逗号拆分元素是否是Python中另一列的子字符串合并两个数据帧,python,python-3.x,pandas,string,dataframe,Python,Python 3.x,Pandas,String,Dataframe,给定数据帧df1,如下所示: 公司名称 行业关键词 鲁尼曲调 化学品、电气设备 阿森一族 信息技术、软件和服务 大豆绿 烟草、饮料 Initech 药品、保健 居民恶 技术 胡里 石油和天然气、能源 杂草 技术、食品 边缘 制造业 首先与一起使用,然后与convert index to column合并以避免丢失值,通过join聚合并添加到原始df1: df11 = df1.assign(industry_keywords = df1['industry_keywords'].str.split
df1
,如下所示:
公司名称
行业关键词
鲁尼曲调
化学品、电气设备
阿森一族
信息技术、软件和服务
大豆绿
烟草、饮料
Initech
药品、保健
居民恶
技术
胡里
石油和天然气、能源
杂草
技术、食品
边缘
制造业
首先与一起使用,然后与convert index to column合并以避免丢失值,通过join
聚合并添加到原始df1
:
df11 = df1.assign(industry_keywords = df1['industry_keywords'].str.split(', ')).explode('industry_keywords')
df22 = df2.assign(industry_keywords = df2['industry_keywords'].str.split(', ')).explode('industry_keywords')
要删除重复项,请使用:
非常感谢,对于第一行的输出,我们得到了两个重复的
second-tier
标签,我们能保留一个吗?对不起,我还有一个问题,如果df2
中的行业关键字在用逗号拆分后,是子字符串或与df1
中的关键字完全相同,然后匹配它们。例如,假设汇丰银行的行业关键词
是银行、金融服务
,我希望它与第三层
匹配,作为其标签
,因为第三层
的行业关键词
元素金融
是金融服务
的子串,有可能吗?
s = (df11.reset_index()
.merge(df22, on='industry_keywords')
.groupby('index')['label']
.agg(', '.join))
df1 = df1.join(s)
print (df1)
company_name industry_keywords \
0 Looney Tunes Chemicals, Electrical Equipment
1 The Simpsons Information Technology, Software & Services
2 Soylent Green Tobacco, Beverages
3 Initech Pharmaceuticals, Health Care
4 Resident Evil Technology
5 Hooli Oil and Gas, Energy
6 Weeds Technology, Food Products
7 Fringe Manufacturing
label
0 second tiers, second tiers
1 third tiers
2 first tiers
3 NaN
4 third tiers
5 second tiers
6 third tiers, first tiers
7 second tiers
s = (df11.reset_index()
.merge(df22, on='industry_keywords')
.drop_duplicates(['index','label'])
.groupby('index')['label']
.agg(', '.join))
df1 = df1.join(s)
print (df1)
company_name industry_keywords \
0 Looney Tunes Chemicals, Electrical Equipment
1 The Simpsons Information Technology, Software & Services
2 Soylent Green Tobacco, Beverages
3 Initech Pharmaceuticals, Health Care
4 Resident Evil Technology
5 Hooli Oil and Gas, Energy
6 Weeds Technology, Food Products
7 Fringe Manufacturing
label
0 second tiers
1 third tiers
2 first tiers
3 NaN
4 third tiers
5 second tiers
6 third tiers, first tiers
7 second tiers