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

如何合并DataFrame行:将Percentage Total Production<20%的行合并为‘Others’

合并DataFrame中占比小于20%的行并标记为"Others"

解决方案代码

假设你已经有了目标DataFrame,以下是实现需求的完整代码:

import pandas as pd

# 模拟原数据(替换成你的实际DataFrame即可)
df = pd.DataFrame({
    "Country": ["India", "Country A", "Country B", "Country C", "Country D"],
    "Percentage Total Production": [21.561239, 18.2, 15.7, 19.5, 25.03]  # 示例数值,实际替换为你的数据
})

# 1. 筛选占比≥20%的行
top_entries = df[df["Percentage Total Production"] >= 20]

# 2. 计算所有占比<20%的行的总和,保留两位小数
others_total = round(df[df["Percentage Total Production"] < 20]["Percentage Total Production"].sum(), 2)

# 3. 创建"Others"行的DataFrame
others_df = pd.DataFrame({
    "Country": ["Others"],
    "Percentage Total Production": [others_total]
})

# 4. 合并结果,重置索引
final_df = pd.concat([top_entries, others_df], ignore_index=True)

# 可选:将百分比列格式化为带%的字符串(匹配需求的显示样式)
final_df["Percentage Total Production"] = final_df["Percentage Total Production"].apply(lambda x: f"{x}%")

print(final_df)

代码说明

  • 筛选高占比行:通过布尔索引df["Percentage Total Production"] >= 20提取出占比不低于20%的条目(这里会保留India)。
  • 计算Others总和:筛选出占比<20%的行,对Percentage Total Production列求和后保留两位小数,得到78.43。
  • 构建Others行:单独创建一个包含"Others"标签和对应总和的DataFrame。
  • 合并结果:用pd.concat将高占比行和Others行合并,重置索引后得到符合要求的最终DataFrame。
  • 格式化百分比:可选步骤将数值转为带%的字符串,让输出更贴合需求的显示效果。

运行上述代码后,你会得到仅包含India: 21.561239%和Others: 78.43%的DataFrame。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 13:03:30