You can perform arithmetic operators like “+
”, “-
”, “*
”, “/
”, and “//
” in a data frame.
Import the library:
import pandas as pd
Read the dataset:
# Expanded data dictionary with 30 samples and new departments
data = {
"WorkerID": list(range(31)),
"Age": [25, None, 35, 30, 24, 28, None, 32, 27, None, 33, 29, 40, 50,
45, 37, 31, 34, 26, 38, 48, 27, 41, 32, 29, 47, 46, 33, 39, 36, 30],
"Salary": [50000, 54000, None, 58000, 45000, 60000, 49000, None, None,
47000, 55000, 60000, 52000, 64000, 51000, 47000, 58000, 54000,
57000, 53000, 60000, 55000, 56000, 59000, 55000, 62000, 61000, 53000, 58000, 56000, 60000],
"Department": ["HR", "Finance", "IT", "HR", "IT", "Finance", "IT",
"HR", "Finance", "HR", "AI", "Marketing", "Business",
"Finance", "IT", "Marketing", "AI", "HR", "Business",
"Finance", "IT", "AI", "HR", "Business", "Marketing", "HR",
"Finance", "IT", "Business", "AI", "HR"]
}
# Convert to DataFrame
df = pd.DataFrame(data).fillna(30) # Fill in the missing values with 30
df['Salary'] = df['Salary'].replace(30, 40000) # Replace the salary to 40000
+
” will concatenate two strings:# Combine Worker ID and Department with a coma between them
df['Worker Department'] = df['WorkerID'].astype(str) + ', ' + df['Department']
print(df['Worker Department'])
Output:
0 0, HR
1 1, Finance
2 2, IT
3 3, HR
4 4, IT
5 5, Finance
6 6, IT
7 7, HR
8 8, Finance
9 9, HR
10 10, AI
11 11, Marketing
12 12, Business
13 13, Finance
14 14, IT
15 15, Marketing
16 16, AI
17 17, HR
18 18, Business
19 19, Finance
20 20, IT
21 21, AI
22 22, HR
23 23, Business
24 24, Marketing
25 25, HR
26 26, Finance
27 27, IT
28 28, Business
29 29, AI
30 30, HR
Name: Worker Department, dtype: object
# Combine the age and salary
df['Salary + Age'] = df['Salary'] + df['Age']
print(df[['Salary', 'Age', 'Salary + Age']])
Output:
Salary Age Salary + Age
0 50000.0 25.0 50025.0
1 54000.0 30.0 54030.0
2 40000.0 35.0 40035.0
3 58000.0 30.0 58030.0
4 45000.0 24.0 45024.0
5 60000.0 28.0 60028.0
6 49000.0 30.0 49030.0
7 40000.0 32.0 40032.0
8 40000.0 27.0 40027.0
9 47000.0 30.0 47030.0
10 55000.0 33.0 55033.0
11 60000.0 29.0 60029.0
12 52000.0 40.0 52040.0
13 64000.0 50.0 64050.0
14 51000.0 45.0 51045.0
15 47000.0 37.0 47037.0
16 58000.0 31.0 58031.0
17 54000.0 34.0 54034.0
18 57000.0 26.0 57026.0
19 53000.0 38.0 53038.0
20 60000.0 48.0 60048.0
21 55000.0 27.0 55027.0
22 56000.0 41.0 56041.0
23 59000.0 32.0 59032.0
24 55000.0 29.0 55029.0
25 62000.0 47.0 62047.0
26 61000.0 46.0 61046.0
27 53000.0 33.0 53033.0
28 58000.0 39.0 58039.0
29 56000.0 36.0 56036.0
30 60000.0 30.0 60030.0