Home > database >  Hierarchical Columns in Numpy
Hierarchical Columns in Numpy

Time:01-17

I'm new to Pandas and trying to recreate the following dataframe, such that values in columns A and B contain random numbers 0 through 8. However, I keep getting "ValueError: all arrays must be same length". Can someone please review my code ? Thank you! DataFrame

df = pd.DataFrame(np.random.randint(0, high=9),index = [[1, 2, 3], ['a', 'b']],
columns = ['A', 'B'])

CodePudding user response:

Since there are two layers to the index, you have to create a multi index:

df = pd.DataFrame(
    np.random.randint(9, size=(6, 2)),
    index=pd.MultiIndex.from_product([[1, 2, 3], ['a', 'b']]),
    columns=['A', 'B']
)

output:

     A  B
1 a  1  0
  b  4  3
2 a  7  3
  b  1  6
3 a  5  4
  b  3  3
  • Related