使用Pandas和Python操作分层数据集
我有一组餐厅销售数据,其结构包括两个维度:位置维度和食物类型维度,以及包含一些度量的事实表。我在操作表以执行分析时遇到问题。最后,它可能会显示在excel中 以下是一个玩具数据集:使用Pandas和Python操作分层数据集,python,pandas,Python,Pandas,我有一组餐厅销售数据,其结构包括两个维度:位置维度和食物类型维度,以及包含一些度量的事实表。我在操作表以执行分析时遇到问题。最后,它可能会显示在excel中 以下是一个玩具数据集: tuples = [('California', 'SF'), ('California', 'SD'), ('New York', 'Roch'), ('New York', 'NY'), ('Texas', 'Houst'), ('Texas', 'SA')] measure1
tuples = [('California', 'SF'), ('California', 'SD'),
('New York', 'Roch'), ('New York', 'NY'),
('Texas', 'Houst'), ('Texas', 'SA')]
measure1 = [5, 10,
30, 60,
10, 30]
measure2 = [50, 10,
30, 6,
1, 30]
tier1 = ['Burger',
'Burger',
'Burger',
'Pizza',
'Pizza',
'Burger']
tier2 = ['Beef',
'Chicken',
'Beef',
'Pep',
'Cheese',
'Beef']
index = pd.MultiIndex.from_tuples(tuples, names=['State', 'City'])
revenue = pd.Series(measure1, index=index)
revenue = revenue.reindex(index)
rev_df = pd.DataFrame({'Category':tier1,
'Subcategory':tier2,
'Revenue': revenue,
'NumOfOrders': [3, 5,1, 3,10, 20]})
rev_df
此代码生成此数据帧:
我想做两件事:
(一) (二) 首先,我的第一次尝试是使用pivot_表
pivoted = rev_df.pivot_table(index = ['State','City'],
columns = ['Category','Subcategory'],
aggfunc = 'sum', #How to make it a weighted average?
margins = True, #How to subtotal and grandtotal?
margins_name = 'All',
fill_value = 0)
KeyError: "['State' 'City'] not in index"
正如你所看到的,我犯了一个错误。python操作这个雪花般的数据模型的最有效方法是什么?这里的问题是州和市是索引名,一个快速的解决方法是在透视之前重置索引,尝试
rev_df.reset_index().pivot…
,也就是说,您可能会得到一个更好的解决方案,如何得到示例(1)第一个单元格中的4
?我想这与你对“加权收入”的定义有关,但我不知道它是如何计算的。原谅我,它们是玩具数字。我想用numOrders-sumproduct(rev,numOrders)/sum(numOrders)来衡量收入。这里的问题是州和市是索引名称,一个快速解决方法是在枢轴之前重置索引,尝试rev_df.reset_index().pivot…
,也就是说,您可能会得到一个更好的解决方案,如何得到示例(1)第一个单元格中的4
?我想这与你对“加权收入”的定义有关,但我不知道它是如何计算的。原谅我,它们是玩具数字。我想通过numOrders-sumproduct(修订版,numOrders)/sum(numOrders)来衡量收入
California California Total
SF SD
Total Burger WgtRev 9 10 19
Beef WgtRev 4 5 10
Chickn WgtRev 5 5 10
Total Pizza...
pivoted = rev_df.pivot_table(index = ['State','City'],
columns = ['Category','Subcategory'],
aggfunc = 'sum', #How to make it a weighted average?
margins = True, #How to subtotal and grandtotal?
margins_name = 'All',
fill_value = 0)
KeyError: "['State' 'City'] not in index"