
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Column Summation of Tuples in Python
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
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
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)]
Advertisements