Ringvold
Ringvold

Reputation: 63

Is it possible to assign a MultiIndex to an empty DataFrame?

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.

Upvotes: 1

Views: 1408

Answers (1)

Ringvold
Ringvold

Reputation: 63

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!)

Upvotes: 1

Related Questions