0

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?

1
  • The input is only w or do you also have a preexisting single-indexed dataframe? Commented Apr 10, 2022 at 18:16

1 Answer 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
Sign up to request clarification or add additional context in comments.

2 Comments

this is helping and getting me foreward! I need to find good sources to learn how to transform DataFrames, have you any suggestions for me?
Try, fail, read the docs, search stackoverflow, try again, succeed ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.