在pandas中创建透视表
有人能帮我创建一个pandas pivot表来获得下面的输出吗 请找到数据框在pandas中创建透视表,pandas,pivot,Pandas,Pivot,有人能帮我创建一个pandas pivot表来获得下面的输出吗 请找到数据框 使用以下代码: result = pd.crosstab(index=df['Product line'], columns=df.City, values=df['Stocked Unit'], aggfunc=np.sum, normalize='columns')\ .applymap(lambda x: f'{100 * x:.2f}%').rename_axis( columns={
使用以下代码:
result = pd.crosstab(index=df['Product line'], columns=df.City,
values=df['Stocked Unit'], aggfunc=np.sum, normalize='columns')\
.applymap(lambda x: f'{100 * x:.2f}%').rename_axis(
columns={'City': None}, index={'Product line': 'Row Labels'})
要点:
-每列中的值之和为1(100%)normalize='columns'
-将分数转换为百分比(带2位小数)applymap(…)
-清除列索引的名称并重命名行索引重命名_轴(…)
result = pd.crosstab(index=wrk['Product line'], columns=wrk.City, values=wrk.Ratio,
aggfunc=np.sum, normalize='columns').applymap(lambda x: f'{100 * x:.2f}%')\
.rename_axis(columns={'City': None}, index={'Product line': 'Row Labels'})\
.reset_index()
Row Labels Mandalay Naypyitaw Yangon
0 Electronic accessories 30.00% 59.89% 28.65%
1 Fashion accessories 30.00% 0.00% 0.00%
2 Food and beverages 40.00% 0.00% 0.00%
3 Health and beauty 0.00% 0.00% 25.55%
4 Home and lifestyle 0.00% 40.11% 22.90%
5 Sports and travel 0.00% 0.00% 22.90%
这能回答你的问题吗?如果您想要百分比,最好将pd.crosstab()与参数normalize='index'或normalize='columns'一起使用。请以书面形式提供样本数据。请描述产生预期产量的逻辑。我需要消耗单位/库存单位之间的百分比计算。不清楚您想要什么。用消耗单位与库存单位的比率替换库存单位的百分比(我计算的)?还是其他方式?另一个暗示是,这对于另一个问题来说相当重要。并提供数据的文本表示形式。我们没有时间从图片中重写您的数据。城市产品线消费单位库存单位仰光健康与美容74.69 522.83内比都电子配件15.28 76.4仰光家庭与生活方式46.33 324.31仰光健康与美容58.22 465.76仰光体育与旅游86.31 604.17内比都电子配件85.39 597.73仰光电子配件68.84 413.04内比都家居与生活73.56 735.6仰光健康与美容36.26 72.52曼德勒食品与饮料54.84 164.52曼德勒时尚配件14.48 57.92曼德勒电子配件25.51 102.04仰光电子配件46.95 234.75仰光
Row Labels Mandalay Naypyitaw Yangon
0 Electronic accessories 30.00% 59.89% 28.65%
1 Fashion accessories 30.00% 0.00% 0.00%
2 Food and beverages 40.00% 0.00% 0.00%
3 Health and beauty 0.00% 0.00% 25.55%
4 Home and lifestyle 0.00% 40.11% 22.90%
5 Sports and travel 0.00% 0.00% 22.90%