1

I've created a MultiIndex and want to create an empty data frame with the MultiIndex as the column labels and then fill the matrix later, but it just returns a regular index with tuples. This code

import pandas as pd

sizes = ['0_200', '200_700', '700_1400', '1400_2300', '2300_4000']
years = [2016, 2020, 2025, 2030, 2035, 2040, 2045, 2050]

multidx = pd.MultiIndex.from_product([sizes, years], names=['size', 'year'])
print(multidx)
df = pd.DataFrame(columns=multidx)
print(df)

yields

MultiIndex(levels=[['0_200', '1400_2300', '200_700', '2300_4000', '700_1400'], [2016, 2020, 2025, 2030, 2035, 2040, 2045, 2050]],
           labels=[[0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 4, 4, 4, 4, 4, 4, 4, 4, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3], [0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7]],
           names=['size', 'year'])

Empty DataFrame
Columns: [(0_200, 2016), (0_200, 2020), (0_200, 2025), (0_200, 2030), (0_200, 2035), (0_200, 2040), (0_200, 2045), (0_200, 2050), (200_700, 2016), (200_700, 2020), (200_700, 2025), (200_700, 2030), (200_700, 2035), (200_700, 2040), (200_700, 2045), (200_700, 2050), (700_1400, 2016), (700_1400, 2020), (700_1400, 2025), (700_1400, 2030), (700_1400, 2035), (700_1400, 2040), (700_1400, 2045), (700_1400, 2050), (1400_2300, 2016), (1400_2300, 2020), (1400_2300, 2025), (1400_2300, 2030), (1400_2300, 2035), (1400_2300, 2040), (1400_2300, 2045), (1400_2300, 2050), (2300_4000, 2016), (2300_4000, 2020), (2300_4000, 2025), (2300_4000, 2030), (2300_4000, 2035), (2300_4000, 2040), (2300_4000, 2045), (2300_4000, 2050)]
Index: []
[0 rows x 40 columns]

I'm using Spyder 3.1.4, Python 3.6.0 64bits on Windows. Pandas version 0.19.2.

2
  • 1
    It is multi index if you print df.columns. Or try df.loc[0,:] = np.arange(40) and then print(df). It's likely that's just how an empty data frame is printed. Commented Jun 6, 2017 at 14:46
  • 1
    Yep, it looks like you were successful in your attempts to create an empty df with multiindex in columns. Commented Jun 6, 2017 at 15:12

1 Answer 1

1

Thank you Psidom and Scott Boston. You're right that the multiindex is there, it just prints as tuples before the data frame is filled. I'll leave this question here because it would have been really handy for me about 24 hours ago. (I'm new here though, so if this counts as a non-question and I should rather delete it, let me know!)

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.