Answers for "pandas add column with sum of certain rows"

2

pandas sum rows

# Basic syntax:
df.sum(axis=1)

# Create new column consisting of row sums across specific columns:
df['sums'] = df.iloc[:, 6:23].sum(axis=1)

# Where:
#	- iloc allows you to specify the rows and columns with slicing. Here
#		I select all rows and sum over columns 6-22
#	- df['sums'] is how you assign a new column named 'sums' to the df

# Example usage:
import pandas as pd
import numpy as np

# Create dataframe:
df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), 
                  columns=['a', 'b', 'c'])

print(df)
   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9

# Sum columns 1-2:
df['sums'] = df.iloc[:, 1:3].sum(axis=1)

print(df)
   a  b  c  sums
0  1  2  3     5
1  4  5  6    11
2  7  8  9    17
Posted by: Guest on May-23-2021
0

how to add the sum of multiple columns into another column in a dataframe

print(df)
   Apples  Bananas  Grapes  Kiwis
0     2.0      3.0     NaN    1.0
1     1.0      3.0     7.0    NaN
2     NaN      NaN     2.0    3.0

df['Fruit Total']=df.iloc[:,-4:].sum(axis=1)

print(df)
   Apples  Bananas  Grapes  Kiwis  Fruit Total
0     2.0      3.0     NaN    1.0          6.0
1     1.0      3.0     7.0    NaN         11.0
2     NaN      NaN     2.0    3.0          5.0
Posted by: Guest on June-03-2020

Code answers related to "pandas add column with sum of certain rows"

Python Answers by Framework

Browse Popular Code Answers by Language