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.

a = 10
b = 5
result = a + b
print(result)  # Output: 15

6.1.2 Subtraction (-)

The subtraction operator subtracts the second number from the first.

a = 10
b = 5
result = a - b
print(result)  # Output: 5

6.1.3 Multiplication (*)

The multiplication operator multiplies two numbers.

a = 10
b = 5
result = a * b
print(result)  # Output: 50

6.1.4 Division (/)

The division operator divides the first number by the second.

a = 10
b = 5
result = a / b
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.

a = 10
b = 3
result = a % b
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.

a = 2
b = 3
result = a ** b
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.

a = 10
b = 3
result = a // b
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.

a = 10
b = 3
quotient, remainder = divmod(a, b)
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]
}
df = pd.DataFrame(data)
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:

df['A_plus_10'] = df['A'] + 10
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:

df['A_minus_C'] = df['A'] - df['C']
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:

df['A_mod_3'] = df['A'] % 3
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 equals 1.
  • For row 1: 20 % 3 equals 2.
  • For row 2: 30 % 3 equals 0.

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:

df[['Quotient', 'Remainder']] = df['A'].apply(lambda x: pd.Series(divmod(x, 3)))
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:

df['Sum_A_B_C'] = df[['A', 'B', 'C']].sum(axis=1)
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:

df['A_squared'] = df['A'].apply(lambda x: x ** 2)
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:

df['A_gt_15'] = df['A'] > 15
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:

df.loc[1, 'B'] = None  # Introduce a NaN value
df['B_plus_2'] = df['B'] + 2
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:

  1. Introducing a Missing Value:

    df.loc[1, 'B'] = None  # Introduce a NaN value

    This line sets the value at row index 1 in column 'B' to None, which pandas treats as NaN (Not a Number). This introduces a missing value in the DataFrame.

  2. Performing Arithmetic with NaN:

    df['B_plus_2'] = df['B'] + 2

    This line creates a new column, 'B_plus_2', by adding 2 to the values in column 'B'. When you perform arithmetic with NaN in pandas, the result for that specific operation is also NaN. This is why in the resulting DataFrame, the row with NaN in column 'B' also has NaN in the new column 'B_plus_2'.

6.2.12 Grouped Operations

Perform operations on grouped data:

df['Group'] = ['X', 'Y', 'X']

print(df)
print('---')

grouped = df.groupby('Group')
sum_per_group = grouped['A'].sum()
print(sum_per_group)

Output:

Group
X    40
Y    20
Name: A, dtype: int64