This may be a duplicate, but I can't find the required answer. So, here's the question:
Suppose, I have got a dataframe like this:
d1 = {'col1': [[1],[2,3]],
'col2' : [[3],[21,1]]}
df1 = pd.DataFrame(d1)
| col1 | col2 | |
|---|---|---|
| 0 | [1] | [3] |
| 1 | [2, 3] | [21, 1] |
Now, we can expand this dataframe vertically very easily via df1.apply(pd.Series.explode).
But, what's the most elegant way to expand in a horizontal direction and change the column names?
Something like this:
d2 = {
'col1_1':[1,2],
'col1_2': [np.NAN,3],
'col2_1' : [3,21],
'col2_2' : [np.NAN,1]
}
df2 = pd.DataFrame(d2)
Output:
| col1_1 | col1_2 | col2_1 | col2_2 | |
|---|---|---|---|---|
| 0 | 1 | NaN | 3 | NaN |
| 1 | 2 | 3.0 | 21 | 1.0 |