我是数据透视表的新手,并且拥有以下数据集:
mydict = {'City' : ['Lexington', 'Lexington', 'Louisville', 'Hartford', 'Portland', 'Dallas'],
'State': ['KY', 'KY', 'KY', 'CT', 'ME', 'TX'],
'Zip': ['38293', '38293', '40207', '48488', '55849', '44930'],
'Region': ['South', 'South', 'South', 'Northeast', 'Northeast', 'South'],
'Sales': [1000, 2000, 3000, 1500, 2000, 2300],
'Product Type': ['Industrial', 'Consumer', 'Consumer', 'Educational', 'Educational', 'Scientific']}
dftest = pd.DataFrame(mydict)
mypivot = pd.pivot_table(dftest, values=['Sales'], index=['State', 'City'])
这将为销售创建一个列。
Sales
State City
CT Hartford 1500
KY Lexington 1500
Louisville 3000
ME Portland 2000
TX Dallas 2300
但我想要的是例如销售下的两列,对应于我的产品类型的临时列表,例如('工业','消费者')。
像这样:
Sales
State City Industrial Consumer
CT Hartford 0 0
KY Lexington 1000 2000
Louisville 0 3000
ME Portland 0 0
TX Dallas 0 0
这可以使用数据透视表吗?还是我必须以某种方式手动构建这样的数据框(我认为这会导致代码过于复杂)?
编辑:
我现在看到 mypivot.columns 返回一个 MultiIndex。我听说过这些,但还不知道如何操作它们。我觉得问题的解决方案在于如何指定 MultiIndex 过滤器。