cobra
cobra

Reputation: 37

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?

Upvotes: 0

Views: 241

Answers (1)

mozway
mozway

Reputation: 260430

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

Upvotes: 1

Related Questions