Python - Column summation of tuples

PythonServer Side ProgrammingProgramming

Python has extensive availability of various libraries and functions which make it so popular for data analysis. We may get a need to sum the values in a single column for a group of tuples for our analysis. So in this program we are adding all the values present at the same position or same column in a series of tuples.

It can be achieved in the following ways.

Using for loop and zip

Using the for loop we loop through each item and apply zip function to gather the values from each column. Then we apply the sum function and finally get the result into a new tuple.

Example

 Live Demo

data = [[(3, 92), (21, 4), (15, 6)],[(25, 62), (12, 7), (15, 7)]]

print("The list of tuples: " + str(data))
# using list comprehension + zip()
result = [tuple(sum(m) for m in zip(*n))
for n in zip(*data)]
print(" Column summation of tuples: " + str(result))

Output

Running the above code gives us the following result:

The list of tuples: [[(3, 92), (21, 4), (15, 6)], [(25, 62), (12, 7), (15, 7)]]
Column summation of tuples: [(28, 154), (33, 11), (30, 13)]

Using map and zip

We can achieve the same result without using for loop and using map function instead.

Example

 Live Demo

data = [[(3, 92), (21, 4), (15, 6)],[(25, 62), (12, 7), (15, 7)]]

print("The list of tuple values: " + str(data))
# using zip() + map()
result = [tuple(map(sum, zip(*n)))
for n in zip(*data)]
print(" Column summation of tuples: " + str(result))

Output

Running the above code gives us the following result:

The list of tuple values: [[(3, 92), (21, 4), (15, 6)], [(25, 62), (12, 7), (15, 7)]]
Column summation of tuples: [(28, 154), (33, 11), (30, 13)]
raja
Published on 02-Jan-2020 10:24:35
Advertisements