I have a DataFrame that looks like this:
| A | B | |
|---|---|---|
| x | 1 | 2 |
| y | 2 | 4 |
| z | 3 | 6 |
What I want is:
| A_x | A_y | A_z | B_x | B_y | B_z |
|---|---|---|---|---|---|
| 1 | 2 | 3 | 2 | 4 | 6 |
Is there a method in Python that allows me to do this? I tried pivot but I don't have an index - I only need one row.
Since @mozway had my exact answer here a different way:
df.unstack().to_frame().T.set_axis(
["_".join([a, b]) for a, b in pd.MultiIndex.from_product([df.columns, df.index])],
axis=1,
)
Try:
dfi = df.unstack().to_frame().T
dfi.columns = dfi.columns.map('_'.join)
dfi
Output:
A_x A_y A_z B_x B_y B_z
0 1 2 3 2 4 6