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

如何按行对指定列求和?含特定列生成总计列的实现方案

Hey there! Let's tackle these two questions about row-wise summation—super common tasks when working with tabular data. Here's how to do it properly using pandas (the standard library for this kind of work in Python):

1. How to sum values in specified columns row-wise?

Row-wise summation is straightforward once you know the right parameter. Here's the breakdown:

  • First, pick the columns you want to sum by passing a list of their names to your DataFrame.
  • Use the sum() method with axis=1—this tells pandas to calculate sums across each row (instead of down columns, which is the default axis=0).
  • By default, sum() skips any missing values (NaN), but if you want missing values to make the total NaN, set skipna=False. If you'd rather treat NaNs as 0, use fillna(0) before summing.

Example code:

# Replace 'df' with your DataFrame name, and the column list with your columns
df['row_total'] = df[['column_a', 'column_b', 'column_c']].sum(axis=1)

# To treat NaNs as 0:
df['row_total'] = df[['column_a', 'column_b', 'column_c']].fillna(0).sum(axis=1)
2. How to sum NYSEARCA:RYE_totalunits and NYSEARCA:PXE_totalunits into a new column 'total overall units'?

This is just a specific instance of the first question. Here's the exact code you can copy-paste (assuming your DataFrame is named df):

df['total overall units'] = df[['NYSEARCA:RYE_totalunits', 'NYSEARCA:PXE_totalunits']].sum(axis=1)

If you want to handle missing values by replacing them with 0 (so rows with NaNs don't end up with a NaN total), modify it like this:

df['total overall units'] = df[['NYSEARCA:RYE_totalunits', 'NYSEARCA:PXE_totalunits']].fillna(0).sum(axis=1)

That's all there is to it—this will create your new column with the row-wise totals of those two specific columns.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:07:11