'Pandas MultiIndex DataFrame
I have an array:
w = np.array([1, 2, 3])
and I need to create a Dataframe with a MultiIndex looking like this:
df= 0 1 2
0 0 1 1 1
1 1 1 1
2 1 1 1
1 0 2 2 2
1 2 2 2
2 2 2 2
2 0 3 3 3
1 3 3 3
2 3 3 3
How can i assign the values of my array to the correct positions in the DataFrame?
Solution 1:[1]
The exact logic is unclear, by assuming w
is the only input and you want to broadcast it as index(0,1) and columns:
w = np.array([1, 2, 3])
N = len(w)
df = pd.DataFrame(np.repeat(w, N**2).reshape((-1,N)),
index=pd.MultiIndex.from_product([np.arange(N)]*2)
)
output:
0 1 2
0 0 1 1 1
1 1 1 1
2 1 1 1
1 0 2 2 2
1 2 2 2
2 2 2 2
2 0 3 3 3
1 3 3 3
2 3 3 3
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | mozway |