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

如何在多行列的Pandas DataFrame末尾添加指定统计值字段?

Solution: Adding a Custom Count Column to Your Pandas DataFrame

Absolutely feasible! This is a super common task in pandas, and it works perfectly even with larger DataFrames (20+ rows, xx+ columns). Let me break down how to pull this off, depending on exactly what you're looking for:

1. Add a column to count specific values per row

If you want to tally how many times a target value appears in each individual row (e.g., counting how many "Yes" entries are in each row), here's the code:

# Replace with your actual DataFrame name and target value
df = your_dataframe_here
target_value = "Yes"  # Could also be a number like 1, or any value matching your data

# Add the new count column at the end of the DataFrame
df["特定值行计数"] = df.apply(lambda row: (row == target_value).sum(), axis=1)

How this works:

  • axis=1 tells pandas to operate row-by-row instead of column-by-column
  • (row == target_value) creates a boolean Series where each cell is True if it matches your target
  • .sum() converts those True values to 1 and adds them up, giving the total per row

For faster performance with very large DataFrames, use this vectorized alternative (avoids the slower apply method):

df["特定值行计数"] = df.isin([target_value]).sum(axis=1)

2. Add a column with the total count of specific values across the entire DataFrame

If you want every row in the new column to show the total number of times your target value appears anywhere in the DataFrame, use this simpler approach:

target_value = "Yes"
# Calculate total occurrences across all rows and columns
global_total = (df == target_value).sum().sum()
# Add the new column with this total repeated in every row
df["全局特定值总数"] = global_total

How this works:

  • The first .sum() counts occurrences per column
  • The second .sum() adds those column totals together to get the overall count
  • Assigning this single value to a new column fills every row with that total

Final Step: Export to Excel

Once you've added your custom count column, just run your existing export command as usual:

df.to_excel("your_output_file.xlsx", index=False)  # index=False removes default row numbers if you don't want them

This will export the DataFrame with your new column included, exactly as you need before writing to Excel.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 08:54:07