Assume, I have a DataFrame with million rows. Here, each row represents one shopper, each number in each cell denotes item code. There are approximately 250 items in the data base. A toy table is like following
import pandas as pd
import numpy as np
df = pd.DataFrame({'item1':[10, 10, 22, 89],
'item2':[15, 35, 33, 103],
'item3':[np.NaN, 65, 47, 41],
'item4':[np.NaN, np.NaN, 10, 22]})
df
| item1 | item2 | item3 | item4 |
|---|---|---|---|
| 10 | 15 | NaN | NaN |
| 10 | 35 | 65 | NaN |
| 22 | 33 | 47 | 10 |
| 89 | 103 | 41 | 22 |
The goal is to convert the above table into a one-hot encoded table/DataFrame (each row still represents one shopper) such as
| 1 | ... | 10 | ... | 15 | ... | 250 |
|---|---|---|---|---|---|---|
| 0 | 0 | 1 | ... | 1 | ... | 0 |
| 0 | 0 | 1 | ... | 0 | ... | 0 |
Thus, the final data frame shape is something like (1000000, 250). Is there a way to convert a DataFrame into a one-hot encoded table quickly?