Python 如果列1不包含列表中的任何子字符串,请将已清理的列2合并到新列中
我的处境很艰难,我需要执行多个操作才能得到一个新的专栏。我有一个子字符串列表。如果“company”列不包含列表中的任何子字符串,我必须将“compnay”和“city”(不带数字)组合成一个“new”列。相反,如果子字符串匹配,“new”将返回“company”列 子字符串列表Python 如果列1不包含列表中的任何子字符串,请将已清理的列2合并到新列中,python,string,append,substring,concat,Python,String,Append,Substring,Concat,我的处境很艰难,我需要执行多个操作才能得到一个新的专栏。我有一个子字符串列表。如果“company”列不包含列表中的任何子字符串,我必须将“compnay”和“city”(不带数字)组合成一个“new”列。相反,如果子字符串匹配,“new”将返回“company”列 子字符串列表 list=['co','co.','ltd','ltd.','limited','inc','inc.'] 当前数据帧 City Company 10001 New York Nike
list=['co','co.','ltd','ltd.','limited','inc','inc.']
当前数据帧
City Company
10001 New York Nike ltd
Paris Louis Vuitton
689 Tokyo Nissan inc.
Milan Ferrari co
999 Hong Kong Li&Fung
Vancouver Lululemon
Seoul Samsung limited
期望输出
City Company New
10001 New York Nike Ltd Nike Ltd
2345 Paris Louis Vuitton Louis Vuitton, Paris
689 Tokyo Nissan inc. Nissan inc.
Milan Ferrari co Ferrari co
999 Hong Kong Li&Fung Li&Fung, Hong Kong
Vancouver Lululemon Lululemon, Vancouver
Seoul Samsung limited Samsung Limited
提前谢谢!感谢您的帮助 使用
pandas.Series.where
,str.contains
和extract
:
l=['co','co.','ltd','ltd.','limited','inc','inc.']
s = df["Company"]
city = df["City"].str.extract("(\D+)",expand=False).str.strip()
df["new"] = s.where(s.str.contains("|".join(l)),
lambda x:x+", "+city)
print(df)
打印(df)
输出:
City Company new
0 10001 New York Nike ltd Nike ltd
1 Paris Louis Vuitton Louis Vuitton, Paris
2 689 Tokyo Nissan inc. Nissan inc.
3 Milan Ferrari co Ferrari co
4 999 Hong Kong Li&Fung Li&Fung, Hong Kong
5 Vancouver Lululemon Lululemon, Vancouver
6 Seoul Samsung limited Samsung limited