You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

筛选True出现次数最多的10个DataFrame列

筛选True出现次数最多的10个列的方法

因为你的DataFrame每列仅包含True或NaN,可以直接通过以下步骤筛选目标列:

  • 计算每列中True的出现次数:利用sum()方法,True会被当作1,NaN会被当作0,求和结果就是该列True的数量。
  • 按次数降序排序,提取前10个列名。
  • 从原DataFrame中取出这10列。

代码示例

假设你的DataFrame名为df:

# 统计每列True的数量
true_counts = df.sum()

# 按数量降序排序,取前10个列名
top_10_col_names = true_counts.sort_values(ascending=False).head(10).index

# 提取这10列的数据
top_10_df = df[top_10_col_names]

补充:处理相同计数的列

如果有多个列的True出现次数相同,想要进一步按列名排序,可以将统计结果转为DataFrame后处理:

# 转成带列名和计数的DataFrame
counts_df = df.sum().reset_index(name='true_count')

# 先按计数降序,再按列名升序排序,取前10列名
top_10_col_names = counts_df.sort_values(
    by=['true_count', 'index'],
    ascending=[False, True]
).head(10)['index']

top_10_df = df[top_10_col_names]

内容的提问来源于stack exchange,提问作者boioboi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 06:21:36