Home  >  Article  >  Backend Development  >  How do I calculate the sum of specific columns across rows in a Pandas DataFrame?

How do I calculate the sum of specific columns across rows in a Pandas DataFrame?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-10 20:37:02493browse

How do I calculate the sum of specific columns across rows in a Pandas DataFrame?

Computing Sum of Rows in a DataFrame for Specific Columns

To address your DataFrame, where you aim to add a column 'e' representing the sum of columns 'a', 'b', and 'd', the appropriate operation using the specified columns and DataFrame is as follows:

df['e'] = df[['a', 'b', 'd']].sum(axis=1, numeric_only=True)

Here, sum(axis=1) computes the sum along each row, effectively adding the values in columns 'a', 'b', and 'd' for each row. The numeric_only=True parameter ensures that only numeric columns are considered, ignoring non-numeric ones like 'c'.

Alternative Approach: Excluding Specific Columns

If you wish to exclude columns from the sum, you can create a list of the desired columns and exclude unwanted ones:

col_list = list(df)
col_list.remove('d')
df['e'] = df[col_list].sum(axis=1)

This approach allows you to select the specific columns for the calculation.

Additional Notes:

  • The provided code requires Pandas version 2.0 to function correctly.
  • The sum method can also be used to compute the sum of entire columns, not just rows.
  • Refer to the Pandas documentation for more details on the sum method: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.sum.html

The above is the detailed content of How do I calculate the sum of specific columns across rows in a Pandas DataFrame?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn