I have a Pandas DataFrame of company names which has the following structure:
import numpy as np
import pandas as pd
df = pd.DataFrame({'name' : ['Nitron', 'Pulset', 'Rotaxi'],
'postal_code' : [1410, 1020, 1310],
'previous_name1' : ['Rotory', np.NaN, 'Datec'],
'previous_name2' : [ np.NaN, 'Cmotor', np.NaN],
'previous_name3' : ['Datec', np.NaN, np.NaN]
})
print(df)
| name | postal_code | previous_name1 | previous_name2 | previous_name3 |
|--------|-------------|----------------|----------------|----------------|
| Nitron | 1410 | Rotory | NaN | Datec |
| Pulset | 1020 | NaN | Cmotor | NaN |
| Rotaxi | 1310 | Cyclip | NaN | NaN |
As you'll notice, a company can have up to three previous names.
My goal is to "denormalize" the above table so that the new DataFrame has the following form:
| name | postal_code |
|--------|-------------|
| Nitron | 1410 |
| Rotory | 1410 |
| Datec | 1410 |
| Pulset | 1020 |
| Cmotor | 1020 |
| Rotaxi | 1310 |
| Cyclip | 1310 |
That is, I want to add a new row for all instances where the previous company names is non-missing and delete the previous names Series afterwards (I also want to add the postal_code
value for each new row).
I'm looking for a description of the method (preferably with code or pseudocode) which will allow me to achieve the above result.