I'm working on a legacy database with a table that looks like this:
| Account | Key1 | Key2 | Key3 | Val1 | Val2 | Val3 |
|---|---|---|---|---|---|---|
| 1 | Home | Work | 555-555-1111 | 555-555-2222 | ||
| 2 | Home | 555-555-3333 | ||||
| 3 | Mobile | Work | Home | 555-555-4444 | 555-555-5555 | 555-555-6666 |
I'd like to transform that into a properly normalized form in Pandas. The desired output looks like this:
| Account | PhoneType | PhoneNumber |
|---|---|---|
| 1 | Home | 555-555-1111 |
| 1 | Work | 555-555-2222 |
| 2 | Home | 555-555-3333 |
| 3 | Mobile | 555-555-4444 |
| 3 | Work | 555-555-5555 |
| 3 | Home | 555-555-6666 |
The following code will create a dataframe to start with:
import pandas as pd
df = pd.DataFrame([
{
"Account": "1",
"Key1": "Home",
"Key2": "Work",
"Val1": "555-555-1111",
"Val2": "555-555-2222"
},
{
"Account": "2",
"Key1": "Home",
"Val1": "555-555-3333"
},
{
"Account": "3",
"Key1": "Mobile",
"Key2": "Work",
"Key3": "Home",
"Val1": "555-555-4444",
"Val2": "555-555-5555",
"Val3": "555-555-6666"
}
])
What's the cleanest / most efficient way to transform the dataframe as indicated above?