Python | Cumulative Columns summation of Records
Last Updated :
05 Apr, 2023
Sometimes, while working with records, we can have a problem in which we need to sum all the columns of a container of lists which are tuples. This kind of application is common in web development domain. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using sum() + list comprehension + zip()
This task can be performed using combination of above functions. In this, we cumulate the like index elements, i.e columns using zip(), and then iterate through them using list comprehension and perform summation using sum().
Python3
test_list = [( 1 , 2 , 3 ), ( 6 , 7 , 6 ), ( 1 , 6 , 8 )]
print ( "The original list : " + str (test_list))
res = [ sum (ele) for ele in zip ( * test_list)]
print ( "The Cumulative column sum is : " + str (res))
|
Output
The original list : [(1, 2, 3), (6, 7, 6), (1, 6, 8)]
The Cumulative column sum is : [8, 15, 17]
The time complexity of the given Python code is O(n), where n is the number of elements in the input list.
The auxiliary space complexity of the code is O(m), where m is the number of columns in the input list.
Method #2 : Using zip() + map() + sum()
This method is similar to the above method. In this, the task performed by list comprehension is performed by map(), which extends the summation of columns to zipped elements.
Python3
test_list = [( 1 , 2 , 3 ), ( 6 , 7 , 6 ), ( 1 , 6 , 8 )]
print ( "The original list : " + str (test_list))
res = list ( map ( sum , zip ( * test_list)))
print ( "The Cumulative column sum is : " + str (res))
|
Output
The original list : [(1, 2, 3), (6, 7, 6), (1, 6, 8)]
The Cumulative column sum is : [8, 15, 17]
The time complexity of this code is O(n), where n is the number of tuples in the input list.
The auxiliary space complexity of this code is O(m), where m is the length of each tuple in the input list.
Method 3 – using a for loop:
In this we method iterates through each column of the input list using the outer loop and calculates the sum of each column using the inner loop. The sum is then appended to the res list.
Python3
test_list = [( 1 , 2 , 3 ), ( 6 , 7 , 6 ), ( 1 , 6 , 8 )]
print ( "The original list : " + str (test_list))
res = []
for i in range ( len (test_list[ 0 ])):
col_sum = 0
for j in range ( len (test_list)):
col_sum + = test_list[j][i]
res.append(col_sum)
print ( "The Cumulative column sum is : " + str (res))
|
Output
The original list : [(1, 2, 3), (6, 7, 6), (1, 6, 8)]
The Cumulative column sum is : [8, 15, 17]
The time complexity of this program is O(n^2), where n is the number of rows or columns in the input list test_list.
The auxiliary space used by this program is O(n), where n is the number of columns in the input list test_list.
Method #4: Using NumPy
NumPy is a Python library used for scientific computing, which includes a powerful N-dimensional array object. We can use the sum() function of NumPy to get the cumulative column sum of the records in the list.
Step-by-step approach:
- Import numpy as np.
- Define the input list test_list containing the records whose cumulative column sum is to be calculated.
- Print the original list using the print() function and the string concatenation operator.
- Convert the input list test_list into a NumPy array using the np.array() function.
- Use the np.sum() function to get the cumulative column sum of the NumPy array. The axis parameter is set to 0 to calculate the sum column-wise.
- Convert the resultant NumPy array into a list using the tolist() method and store it in the res variable.
- Print the final result using the print() function and the string concatenation operator.
Below is the implementation of the above approach:
Python3
import numpy as np
test_list = [( 1 , 2 , 3 ), ( 6 , 7 , 6 ), ( 1 , 6 , 8 )]
print ( "The original list : " + str (test_list))
arr = np.array(test_list)
res = np. sum (arr, axis = 0 ).tolist()
print ( "The Cumulative column sum is : " + str (res))
|
OUTPUT:
The original list : [(1, 2, 3), (6, 7, 6), (1, 6, 8)]
The Cumulative column sum is : [8, 15, 17]
Time complexity: O(n*m), where n is the number of rows and m is the number of columns in the input list.
Auxiliary space: O(n*m), where n is the number of rows and m is the number of columns in the input list, due to the creation of the NumPy array.
Method 6 : using the pandas library.
- The pandas.DataFrame() function is used to convert the list of tuples to a pandas DataFrame object.
- The DataFrame.sum() method is used to calculate the sum of each column of the DataFrame.
- The tolist() method is used to convert the resulting pandas Series object to a list.
Python3
import pandas as pd
test_list = [( 1 , 2 , 3 ), ( 6 , 7 , 6 ), ( 1 , 6 , 8 )]
df = pd.DataFrame(test_list)
res = df. sum ().tolist()
print ( "The original list : " + str (test_list))
print ( "The Cumulative column sum is : " + str (res))
|
OUTPUT:
The original list : [(1, 2, 3), (6, 7, 6), (1, 6, 8)]
The Cumulative column sum is : [8, 15, 17]
Time complexity: O(nm), where n is the number of tuples in the list and m is the number of elements in each tuple.
Auxiliary space complexity: O(nm), where n is the number of tuples in the list and m is the number of elements in each tuple.
Method 7: using the reduce() function:
- Initialize the test_list.
- Print the original test_list.
- Define the lambda function for adding two tuples.
- Use reduce() method to apply the lambda function cumulatively to the elements of the test_list. The result of each step is passed as the first parameter to the next step.
- The final result is stored in res.
- Print the final result, which is the cumulative sum of the columns in the test_list.
Python3
from functools import reduce
test_list = [( 1 , 2 , 3 ), ( 6 , 7 , 6 ), ( 1 , 6 , 8 )]
print ( "The original list : " + str (test_list))
res = reduce ( lambda x, y: [x[i] + y[i]
for i in range ( len (test_list[ 0 ]))], test_list)
print ( "The Cumulative column sum is : " + str (res))
|
Output
The original list : [(1, 2, 3), (6, 7, 6), (1, 6, 8)]
The Cumulative column sum is : [8, 15, 17]
Time Complexity: The time complexity of this implementation is O(mn), where m is the length of the input list and n is the length of the tuples in the list. The reduce() function iterates over all m tuples and performs n additions for each tuple.
Space Complexity: The space complexity of this implementation is O(n), where n is the length of the tuples in the input list. The reduce() function creates a single tuple to store the cumulative column sums.
Similar Reads
Summation Matrix columns - Python
The task of summing the columns of a matrix in Python involves calculating the sum of each column in a 2D list or array. For example, given the matrix a = [[3, 7, 6], [1, 3, 5], [9, 3, 2]], the goal is to compute the sum of each column, resulting in [13, 13, 13]. Using numpy.sum()numpy.sum() is a hi
2 min read
Python - Summation of kth column in a matrix
Sometimes, while working with Python Matrix, we may have a problem in which we require to find the summation of a particular column. This can have a possible application in day-day programming and competitive programming. Letâs discuss certain ways in which this task can be performed. Method #1 : Us
8 min read
Python - Tuple Matrix Columns Summation
Sometimes, while working with Tuple Matrix, we can have a problem in which we need to perform summation of each column of tuple matrix, at the element level. This kind of problem can have application in Data Science domains. Let's discuss certain ways in which this task can be performed. Input : tes
8 min read
Python - Consecutive Row summation in Matrix
This particular article focuses on a problem that has utility in competitive as well as day-day programming. Sometimes, we need to get the sum between the like indices when compared with the next list. The sum between the like elements in that index is returned. Letâs discuss certain ways in which t
5 min read
Python | Column summation of tuples
Sometimes, we encounter a problem where we deal with a complex type of matrix column summation in which we are given a tuple and we need to perform the summation of its like elements. This has a good application in Machine Learning domain. Let's discuss certain ways in which this can be done. Method
7 min read
Python Program to Sort Matrix by Sliced Row and Column Summation
Given a Matrix and a range of indices, the task is to write a python program that can sort a matrix on the basis of the sum of only given range of indices of each row and column i.e. the rows and columns are to sliced from a given start to end index, further, matrix are sorted using only those slice
8 min read
Python | Column summation in uneven sized lists
The usual list of list, unlike conventional C type Matrix, can allow the nested list of lists with variable lengths, and when we require the summation of its columns, the uneven length of rows may lead to some elements in that element to be absent and if not handled correctly, may throw exception. L
7 min read
Python | Summation of Kth Column of Tuple List
Sometimes, while working with Python list, we can have a task in which we need to work with tuple list and get the possible accumulation of its Kth index. This problem has applications in the web development domain while working with data information. Let's discuss certain ways in which this task ca
7 min read
Python | Accumulative index summation in tuple list
Sometimes, while working with data, we can have a problem in which we need to find accumulative summation of each index in tuples. This problem can have applications in web development and competitive programming domain. Let's discuss certain way in which this problem can be solved. Method 1: Using
8 min read
Python | Column wise sum of nested list
Given a nested list (where sublists are of equal length), write a Python program to find the column-wise sum of the given list and return it in a new list. Examples: Input : [[1, 5, 3], [2, 7, 8], [4, 6, 9]] Output : [7, 18, 20] Input : [[20, 5], [2, 54], [45, 9], [72, 3]] Output : [139, 71] Method
3 min read