我有下表:

Brand Product
0 Nike Shoes
1 Nike Socks
2 Adidas Shoes
3 Adidas Shoes
4 Adidas Socks
5 Flight Shorts

我想使用Pandas GroupBy函数生成下表(行和列的总计),以找出特定品牌-产品对出现的次数.

Shoes Socks Shorts Total
Nike 1 1 0 2
Adidas 2 1 0 3
Flight 0 0 1 1
Total 3 2 1 6

然后想要按百分比转换单元格:

  • 单元格百分比来自于将单元格值除以列总数(例如,{鞋,阿迪达斯}=2/3=67%或{总,阿迪达斯}=3/6=50%)
Shoes Socks Shorts Total
Nike 50% 50% 0% 33%
Adidas 67% 50% 0% 50%
Flight 0% 0% 100% 17%
Total 100% 100% 100% 100%

最后,有没有办法将所有单元格编号乘以一个调整系数(例如,0.75)

推荐答案

试一试pd.crosstab:

out = pd.crosstab(df["Brand"], df["Product"])
out["Total"] = out.sum(axis=1)
out.index.name, out.columns.name = None, None
print(out)

打印:

        Shoes  Shorts  Socks  Total
Adidas      2       0      1      3
Flight      0       1      0      1
Nike        1       0      1      2

编辑:要获得百分比,可以在之后执行以下操作:

out.iloc[:, :-1] = (
    out.iloc[:, :-1]
    .div(out["Total"], axis=0)
    .mul(100)
    .round(0)
    .astype(int)
    .astype(str)
    + "%"
)

out["Total"] = (
    out["Total"]
    .div(out["Total"].sum())
    .mul(100)
    .round(0)
    .astype(int)
    .astype(str)
    + "%"
)

打印:

       Shoes Shorts Socks Total
Adidas   67%     0%   33%   50%
Flight    0%   100%    0%   17%
Nike     50%     0%   50%   33%

Python相关问答推荐

pandas DataFrame GroupBy.diff函数的意外输出

根据不同列的值在收件箱中移动数据

对某些列的总数进行民意调查,但不单独列出每列

如何使用数组的最小条目拆分数组

删除字符串中第一次出现单词后的所有内容

cv2.matchTemplate函数匹配失败

Pandas—在数据透视表中占总数的百分比

连接一个rabrame和另一个1d rabrame不是问题,但当使用[...]'运算符会产生不同的结果

如何指定列数据类型

与命令行相比,相同的Python代码在Companyter Notebook中运行速度慢20倍

在单次扫描中创建列表

在输入行运行时停止代码

用两个字符串构建回文

Seaborn散点图使用多个不同的标记而不是点

PYTHON中的pd.wide_to_long比较慢

无法在盐流道中获得柱子

将鼠标悬停在海运`pairplot`的批注/高亮显示上

Django REST框架+Django Channel->;[Errno 111]连接调用失败(';127.0.0.1';,6379)

Fake pathlib.使用pyfakefs的类变量中的路径'

Pandas查找给定时间戳之前的最后一个值