如何按行对指定列求和?含特定列生成总计列的实现方案
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):
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 withaxis=1—this tells pandas to calculate sums across each row (instead of down columns, which is the defaultaxis=0). - By default,
sum()skips any missing values (NaN), but if you want missing values to make the totalNaN, setskipna=False. If you'd rather treat NaNs as 0, usefillna(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)
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

