6 Basic Arithmetic Operations in Python
Arithmetic operations are fundamental to programming and are used to perform mathematical computations. Python provides straightforward syntax for these operations, making it easy to perform calculations with numbers and data structures like DataFrames.
6.1 Simple Examples with Numbers
6.1.1 Addition (+
)
The addition operator adds two numbers together.
= 10
a = 5
b = a + b
result print(result) # Output: 15
6.1.2 Subtraction (-
)
The subtraction operator subtracts the second number from the first.
= 10
a = 5
b = a - b
result print(result) # Output: 5
6.1.3 Multiplication (*
)
The multiplication operator multiplies two numbers.
= 10
a = 5
b = a * b
result print(result) # Output: 50
6.1.4 Division (/
)
The division operator divides the first number by the second.
= 10
a = 5
b = a / b
result print(result) # Output: 2.0
6.1.5 Modulus (%
)
The modulus operator returns the remainder of the division of the first number by the second.
= 10
a = 3
b = a % b
result print(result) # Output: 1
6.1.5.1 Example Explanation
In this example, 10 % 3
computes the remainder when 10 is divided by 3, which is 1.
6.1.6 Exponentiation (**
)
The exponentiation operator raises the first number to the power of the second.
= 2
a = 3
b = a ** b
result print(result) # Output: 8
6.1.7 Floor Division (//
)
The floor division operator divides and returns the largest integer less than or equal to the result.
= 10
a = 3
b = a // b
result print(result) # Output: 3
6.1.8 divmod()
Function
The divmod()
function returns a tuple containing the quotient and the remainder when dividing two numbers.
= 10
a = 3
b = divmod(a, b)
quotient, remainder print(f"Quotient: {quotient}, Remainder: {remainder}")
# Output: Quotient: 3, Remainder: 1
6.1.8.1 Example Explanation
Here, divmod(10, 3)
returns (3, 1)
, where 3
is the quotient and 1
is the remainder when 10 is divided by 3.
6.1.9 Summary Table
Operator/Function | Description | Example | Output |
---|---|---|---|
+ |
Addition | 10 + 5 |
15 |
- |
Subtraction | 10 - 5 |
5 |
* |
Multiplication | 10 * 5 |
50 |
/ |
Division | 10 / 5 |
2.0 |
% |
Modulus (Remainder) | 10 % 3 |
1 |
** |
Exponentiation | 2 ** 3 |
8 |
// |
Floor Division | 10 // 3 |
3 |
divmod() |
Quotient and Remainder as a Tuple | divmod(10, 3) |
(3, 1) |
6.2 Advanced Examples with DataFrames
In data analysis, we often work with tabular data. The pandas
library provides a powerful DataFrame
object to handle such data. Arithmetic operations can be applied to DataFrame
objects directly, enabling efficient data manipulation.
6.2.1 Setting Up the Environment
First, install and import the necessary library:
# Install pandas if not already installed
# !pip install pandas
import pandas as pd
6.2.2 Creating a DataFrame
Let’s create a simple DataFrame
for demonstration:
= {
data 'A': [10, 20, 30],
'B': [1, 2, 3],
'C': [5, 4, 3]
}= pd.DataFrame(data)
df print(df)
Output:
A B C
0 10 1 5
1 20 2 4
2 30 3 3
6.2.3 Adding a Constant to a Column
You can add a constant value to an entire column:
'A_plus_10'] = df['A'] + 10
df[print(df)
Output:
A B C A_plus_10
0 10 1 5 20
1 20 2 4 30
2 30 3 3 40
6.2.4 Column-Wise Operations
Perform arithmetic operations between columns:
'A_minus_C'] = df['A'] - df['C']
df[print(df)
Output:
A B C A_plus_10 A_minus_C
0 10 1 5 20 5
1 20 2 4 30 16
2 30 3 3 40 27
6.2.5 Using Modulus Operator with DataFrames
Apply the modulus operator to a DataFrame column to get the remainder of division element-wise:
'A_mod_3'] = df['A'] % 3
df[print(df)
Output:
A B C A_plus_10 A_minus_C A_mod_3
0 10 1 5 20 5 1
1 20 2 4 30 16 2
2 30 3 3 40 27 0
6.2.5.1 Example Explanation
- For row 0:
10 % 3
equals1
. - For row 1:
20 % 3
equals2
. - For row 2:
30 % 3
equals0
.
6.2.6 Using divmod()
with DataFrames
While divmod()
isn’t directly applicable to DataFrame columns, you can achieve similar results using apply
along with a lambda function:
'Quotient', 'Remainder']] = df['A'].apply(lambda x: pd.Series(divmod(x, 3)))
df[[print(df)
Output:
A B C A_plus_10 A_minus_C A_mod_3 Quotient Remainder
0 10 1 5 20 5 1 3 1
1 20 2 4 30 16 2 6 2
2 30 3 3 40 27 0 10 0
6.2.6.1 Example Explanation
- For row 0:
divmod(10, 3)
returns(3, 1)
. - For row 1:
divmod(20, 3)
returns(6, 2)
. - For row 2:
divmod(30, 3)
returns(10, 0)
.
6.2.7 Row-Wise Operations
Use the sum
function to perform operations across rows:
'Sum_A_B_C'] = df[['A', 'B', 'C']].sum(axis=1)
df[print(df)
Output:
A B C A_plus_10 A_minus_C A_mod_3 Quotient Remainder Sum_A_B_C
0 10 1 5 20 5 1 3 1 16
1 20 2 4 30 16 2 6 2 26
2 30 3 3 40 27 0 10 0 36
6.2.8 Applying Functions
Apply a function to a column:
'A_squared'] = df['A'].apply(lambda x: x ** 2)
df[print(df)
Output:
A B C A_plus_10 A_minus_C A_mod_3 Quotient Remainder Sum_A_B_C A_squared
0 10 1 5 20 5 1 3 1 16 100
1 20 2 4 30 16 2 6 2 26 400
2 30 3 3 40 27 0 10 0 36 900
6.2.9 Conditional Operations
Use conditions to modify data:
'A_gt_15'] = df['A'] > 15
df[print(df)
Output:
A B C A_plus_10 A_minus_C A_mod_3 Quotient Remainder Sum_A_B_C A_squared A_gt_15
0 10 1 5 20 5 1 3 1 16 100 False
1 20 2 4 30 16 2 6 2 26 400 True
2 30 3 3 40 27 0 10 0 36 900 True
6.2.10 Handling Missing Data
Arithmetic operations handle missing data (NaN
) gracefully:
1, 'B'] = None # Introduce a NaN value
df.loc['B_plus_2'] = df['B'] + 2
df[print(df)
Output:
A B C A_plus_10 A_minus_C A_mod_3 Quotient Remainder Sum_A_B_C A_squared A_gt_15 B_plus_2
0 10 1.0 5 20 5 1 3 1 16.0 100 False 3.0
1 20 NaN 4 30 16 2 6 2 NaN 400 True NaN
2 30 3.0 3 40 27 0 10 0 36.0 900 True 5.0
This code snippet demonstrates how to introduce a missing value (NaN
) into a DataFrame and perform an arithmetic operation on a column that contains NaN
values. Let me break down the key points:
6.2.11 Explanation of Code:
Introducing a Missing Value:
1, 'B'] = None # Introduce a NaN value df.loc[
This line sets the value at row index
1
in column'B'
toNone
, which pandas treats asNaN
(Not a Number). This introduces a missing value in the DataFrame.Performing Arithmetic with NaN:
'B_plus_2'] = df['B'] + 2 df[
This line creates a new column,
'B_plus_2'
, by adding2
to the values in column'B'
. When you perform arithmetic withNaN
in pandas, the result for that specific operation is alsoNaN
. This is why in the resulting DataFrame, the row withNaN
in column'B'
also hasNaN
in the new column'B_plus_2'
.
6.2.12 Grouped Operations
Perform operations on grouped data:
'Group'] = ['X', 'Y', 'X']
df[
print(df)
print('---')
= df.groupby('Group')
grouped = grouped['A'].sum()
sum_per_group print(sum_per_group)
Output:
Group
X 40
Y 20
Name: A, dtype: int64