Problem Formulation and Solution Overview
As a Pythonista, coding issues may occur where you need to apply a function against array/matrix elements.
The organization Happy Mortgages has six (6) different Mortgage Terms available:
The US Federal Reserve has decided to increase the Mortgage Rate by 1.23%.
💬 Question: How would we update the Array/Matrix entries to increase the matrix/array elements accordingly?
We can accomplish this task by one of the following options:
- Method 1: Use List Comprehension
- Method 2: Use a
- Method 3: Use a
Consider the following related tutorial if you want to apply a function to column elements instead of the matrix or array.
Related Tutorial: How to Apply a Function to Column Elements?
- The Pandas library enables access to/from a DataFrame.
To install this library, navigate to an IDE terminal. At the command prompt (
$), execute the code below. For the terminal used in this example, the command prompt is a dollar sign (
$). Your terminal prompt may be different.
$ pip install pandas
<Enter> key on the keyboard to start the installation process.
If the installation was successful, a message displays in the terminal indicating the same.
Feel free to view the PyCharm installation guide for the required library.
Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.
import pandas as pd
Method 1: Use List Comprehension
List Comprehension offers a single-line expression to change all the Mortgage Rates in one fell swoop!
m_terms = [30, 20, 15, 10, 7, 5] m_rates = [4.6, 4.3, 3.6, 4.7, 3.8, 3.9] m_rates = [round(x*.0123+x, 3) for x in m_rates] print(m_rates)
Above is a list of Mortgage Terms (
m_terms) available for the six (6) existing Mortgage Rates (
In our code, List Comprehension loops through
m_rates applying the Mortgage Rate increase to each element accordingly. The
round() method trims the decimal places to three (3). The results save back to
Method 2: Use Map and a Lambda
m_terms = [30, 20, 15, 10, 7, 5] m_rates = [4.6, 4.3, 3.6, 4.7, 3.8, 3.9] m_rates = list(map(lambda x : round(x*.0123+x, 3), m_rates)) print(m_rates)
Method 3: Use a For Loop and enumerate()
m_terms = [30, 20, 15, 10, 7, 5] m_rates = [4.6, 4.3, 3.6, 4.7, 3.8, 3.9] for index, item in enumerate(m_rates): m_rates[index] = round(m_rates[index]*.0123+m_rates[index], 3) print (m_rates)
This code loops through
m_rates and applies the Mortgage Rate increase to each element.
round() method trims the decimal places to three (3). Each element saves accordingly.
In case you need a quick refresher on the
enumerate() function, have a look at this video tutorial:
Python One-Liners Book: Master the Single Line First!
Python programmers will improve their computer science skills with these useful one-liners.
Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.
The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.
Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.
You’ll also learn how to:
- Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
- Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
- Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
- Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
- Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting
By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.
At university, I found my love of writing and coding. Both of which I was able to use in my career.
During the past 15 years, I have held a number of positions such as:
In-house Corporate Technical Writer for various software programs such as Navision and Microsoft CRM
Corporate Trainer (staff of 30+)
Implementation Specialist for Navision and Microsoft CRM
Senior PHP Coder