Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Normalize Names

I am using pandas dataframes and I have data where I have customers per company. However, the company titles vary slightly but ultimately affect the data. Example:

Company    Customers
AAAB       1,000
AAAB Inc.  900
The AAAB Inc.  20
AAAB the INC   10

I want to get the total customers out of a data base of several different companies with the companies having non-standard names. Any idea where I should start?

like image 553
Alexis_Kiwis Avatar asked Oct 17 '13 21:10

Alexis_Kiwis


2 Answers

I remember reading this blog about the fuzzywuzzy library (looking into another question), which can do this:

pip install fuzzywuzzy

You can use its partial_ratio function to "fuzzy match" the strings:

In [11]: from fuzzywuzzy.fuzz import partial_ratio

In [12]: partial_ratio('AAAB', 'the AAAB inc.')
Out[12]: 100

Which seems confident about it being a good match!

In [13]: partial_ratio('AAAB', 'AAPL')
Out[13]: 50

In [14]: partial_ratio('AAAB', 'Google')
Out[14]: 0

We can take the best match in the actual company list (assuming you have it):

In [15]: co_list = ['AAAB', 'AAPL', 'GOOG']

In [16]: df.Company.apply(lambda mistyped_co: max(co_list, 
                                                  key=lambda co: partial_ratio(mistyped_co, co)))
Out[16]: 
0    AAAB
1    AAAB
2    AAAB
3    AAAB
Name: Company, dtype: object

I strongly suspect there is something in scikit learn or a numpy library to do this more efficiently on large datasets... but this should get the job done.

If you don't have the company list you'll probably have to do something more clevererer...

like image 176
Andy Hayden Avatar answered Oct 11 '22 17:10

Andy Hayden


splitCompaniesSet = map( lambda cmpnyName : 
    set( map( lambda name : name.split(" "), cmpnyName ) ), dataFrame['Company'] )

I think that's right.

Basically create a list of sets, each set has the company name split. Then, starting with the first element, find the set intersection of every other element with that one. For every non-empty intersection, change the name to whatever the simplest match was among all the non-empty resulting sets, i.e. take one more set intersection with all the nonempty sets and set the result to be the company name for all those non-empty matches.

Then go on to the next Company that resulted in an empty set when intersected with the first company name. Then do this for the next Company that was empty for the first two you tried, and so on.

There's probably a more efficient way to do it, though.

like image 32
Matthew Turner Avatar answered Oct 11 '22 16:10

Matthew Turner