我有一个数据框架df与列名-公司。一些公司名称的例子是:ABC Inc., XYZ Gmbh, PQR Ltd, JKL Limited等。我需要一份所有后缀(Inc.,Gmbh, Ltd, Limited等)的列表。请注意,后缀长度总是不同的。有些公司可能没有后缀,例如:Apple。我需要一个包含所有公司名称后缀的完整列表,列表中只保留唯一的后缀。
我如何完成这个任务?
try this:
In [36]: df
Out[36]:
Company
0 Google
1 Apple Inc
2 Microsoft Inc
3 ABC Inc.
4 XYZ Gmbh
5 PQR Ltd
6 JKL Limited
In [37]: df.Company.str.extract(r's+([^s]+$)', expand=False).dropna().unique()
Out[37]: array(['Inc', 'Inc.', 'Gmbh', 'Ltd', 'Limited'], dtype=object)
或忽略标点符号:
In [38]: import string
In [39]: df.Company.str.replace('['+string.punctuation+']+','')
Out[39]:
0 Google
1 Apple Inc
2 Microsoft Inc
3 ABC Inc
4 XYZ Gmbh
5 PQR Ltd
6 JKL Limited
Name: Company, dtype: object
In [40]: df.Company.str.replace('['+string.punctuation+']+','').str.extract(r's+([^s]+$)', expand=False).dropna().unique()
Out[40]: array(['Inc', 'Gmbh', 'Ltd', 'Limited'], dtype=object)
导出结果到Excel文件:
data = df.Company.str.replace('['+string.punctuation+']+','').str.extract(r's+([^s]+$)', expand=False).dropna().unique()
res = pd.DataFrame(data, columns=['Comp_suffix'])
res.to_excel(r'/path/to/file.xlsx', index=False)
你可以使用cleanco Python库,它里面有一个所有可能的后缀列表。例如,它包含了您提供的所有示例(Inc, Gmbh, Ltd, Limited)。
所以你可以从库中获取后缀,并将它们用作字典来搜索数据,例如:
import pandas as pd
company_names = pd.Series(["Apple", "ABS LLC", "Animusoft Corp", "A GMBH"])
suffixes = ["llc", "corp", "abc"] # take from cleanco source code
found = [any(company_names.map(lambda x: x.lower().endswith(' ' + suffix))) for suffix in suffixes]
suffixes_found = [suffix for (suffix, suffix_found) in zip(suffixes, found) if suffix_found]
print suffixes_found # outputs ['llc', 'corp']
假设公司的名称超过一个单词,那么您想要公司名称的最后一个单词?
set(name_list[-1] for name_list in map(str.split, company_names) if len(name_list) > 1)
[-1]
得到最后一个单词。str.split
在空格上分裂。我从来没有使用过熊猫,所以获得company_names
可能是最难的部分。
这只在公司名称包含多个单词时添加后缀。
company_names = ["Apple", "ABS LLC", "Animusoft Corp"]
suffixes = [name.split()[-1] for name in company_names if len(name.split()) > 1]
现在考虑到这并没有涵盖唯一的需求。这并没有涵盖你可以有一个像"聪明"这样的公司名字,"聪明"不是后缀,而是名称的一部分。然而,这满足了唯一的需求:
company_names = ["Apple", "ABS LLC", "Animusoft Corp", "BBC Corp"]
suffixes = []
for name in company_names:
if len(name.split()) > 1 and name.split()[-1] not in suffixes:
suffixes.append(name.split()[-1])