Note that I was worried when I wanted to convert the grid data.
There is such grid data
import pandas as pd
df = pd.DataFrame(
np.arange(9).reshape(3, 3),
index=["y01", "y02", "y03"],
columns=["x01", "x02", "x03"]
)
x01 | x02 | x03 | |
---|---|---|---|
y01 | 0 | 1 | 2 |
y02 | 3 | 4 | 5 |
y03 | 6 | 7 | 8 |
I want to convert this like this.
column0 | column1 | column2 |
---|---|---|
y01 | x01 | 0 |
y01 | x02 | 1 |
y01 | x03 | 2 |
y02 | x01 | 3 |
y02 | x02 | 4 |
y02 | x03 | 5 |
y03 | x01 | 6 |
y03 | x02 | 7 |
y03 | x03 | 8 |
In pandas, you can use the following method.
df.stack().reset_index()
Then it comes out like this.
level_0 | level_1 | 0 | |
---|---|---|---|
0 | y01 | x01 | 0 |
1 | y01 | x02 | 1 |
2 | y01 | x03 | 2 |
3 | y02 | x01 | 3 |
4 | y02 | x02 | 4 |
5 | y02 | x03 | 5 |
6 | y03 | x01 | 6 |
7 | y03 | x02 | 7 |
8 | y03 | x03 | 8 |
Happy !! Please let me know if there is a better way
Recommended Posts