1

Suppose x = pd.DataFrame({'a': range(0,3), 'b': range(1, 4)}) and y = pd.DataFrame({'a': range(-1,2), 'b': range(2, 5)}). I want to construct a dataframe t = pd.DataFrame('x': x, 'y': y). The expected result is a multiindexed dataframe. However, an error message tells me ValueError: If using all scalar values, you must pass an index.

import panda as pd
x = pd.DataFrame({'a': range(0,3), 'b': range(1, 4)})
y = pd.DataFrame({'a': range(-1,2), 'b': range(2, 5)}) 
t = pd.DataFrame('x': x, 'y': y)

1 Answer 1

2

I believe need concat by indexes (dafault axis=0 is omited) for MultiIndex in indices:

t = pd.concat({'x': x, 'y': y})

Or:

t = pd.concat([x, y], keys=('x','y'))

print (t)

     a  b
x 0  0  1
  1  1  2
  2  2  3
y 0 -1  2
  1  0  3
  2  1  4

Or by columns by axis=1 for MultiIndex in columns:

t = pd.concat({'x': x, 'y': y}, axis=1)
t = pd.concat([x, y], keys=('x','y'), axis=1)

print (t)
   x     y   
   a  b  a  b
0  0  1 -1  2
1  1  2  0  3
2  2  3  1  4
Sign up to request clarification or add additional context in comments.

Comments

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.