我已经创建了一个MultiIndex,并且想要创建一个以MultiIndex作为列标签的空数据框,然后在以后填充矩阵,但是它只是返回带有元组的常规索引。此代码
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)
产量
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]
我在Windows上使用Spyder 3.1.4,Python 3.6.0 64位。熊猫版本0.19.2。
最佳答案
谢谢Psidom和Scott Boston。没错,multiindex就在那里,它只是在填充数据框之前打印为元组。我将在这里留下这个问题,因为大约24小时前它对我来说真的很方便。 (尽管我是新来的,所以如果这算是一个非问题,我宁愿删除它,请告诉我!)
关于python - 是否可以将MultiIndex分配给一个空的DataFrame?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44393121/