python - 根据条件或值计算列中值的百分比
问题描述
我有下面的表格,我想获得 >= 10 秒或更长时间的每种类型的 %。什么是有效的模块化代码?我通常只会过滤每种类型然后除以,但想知道是否有更好的方法来计算类型列中每个值的百分比 >= 10 秒或更多。
谢谢
Type | Seconds
A 23
V 10
V 10
A 7
B 1
V 10
B 72
A 11
V 19
V 3
expected output:
type %
A .67
V .80
B .50
解决方案
一个稍微更有效的选择是创建一个布尔掩码Seconds.ge(10)
并groupby.mean()
在掩码上使用:
df.Seconds.ge(10).groupby(df.Type).mean().reset_index(name='%')
# Type %
# 0 A 0.666667
# 1 B 0.500000
# 2 V 0.800000
鉴于这些功能:
mask_groupby_mean = lambda df: df.Seconds.ge(10).groupby(df.Type).mean().reset_index(name='%')
groupby_apply = lambda df: df.groupby('Type').Seconds.apply(lambda x: (x.ge(10).sum() / len(x)) * 100).reset_index(name='%')
set_index_mean = lambda df: df.set_index('Type').ge(10).mean(level=0).rename(columns={'Seconds': '%'}).reset_index()
推荐阅读
- angular - Angular - 动态组件
- javascript - 如何在不检索文档的情况下检查文档是否存在:Mongoose
- python - Pandas 识别数据框中存在 False 的列表中的行号
- keystonejs - KeystoneJS 不会将 LESS 文件自动编译为 CSS
- python - 如何根据调用者将堆栈级别分配给警告?
- python - 使用官方 sdk-python 时将 md5 授权为 sha512 更新
- ios - UITableView 分隔符出现在单元格中间
- document - 如何使用java在open office中生成word文档?
- typescript - TypeScript:如何在方法内“更改”方法参数的类型?
- android - 有没有办法连续运行服务?