-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterpolation.py
63 lines (52 loc) · 1.85 KB
/
interpolation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Module Name: Linear Interpolation
Description: A brief demo of inspecting, handling, imputating Missing Data, i.e. 'NaN', with Linear Interpolation.
Credit / Prepared by:
Sun CHUNG, SMIEEE
M.Sc., HKU
License: MIT License
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Sample time series data with missing values
dates = pd.date_range(start='2020-01-01', end='2020-01-10')
sales = [200, np.nan, 210, np.nan, np.nan, 250, 260, np.nan, 280, 290]
data = pd.DataFrame({'date': dates, 'sales': sales})
print("Original Data:")
data
### By Observing this example, we know it is 'sales' data with the most missing data.
# Check for missing values
missing_data = data['sales'].isnull().sum()
total_data = len(data)
missing_percentage = (missing_data / total_data) * 100
print("\nMissing Values in Each Column:")
print(data.isnull().sum())
print(f"Percentage of Missing Data: {missing_percentage:.2f}%")
# Plot the original data to observe its shape
plt.figure(figsize=(10, 5))
plt.plot(data['date'], data['sales'], label='Original Sales', marker='o')
plt.title('Original Sales Data with Missing Values')
plt.xlabel('Date')
plt.ylabel('Sales')
plt.legend()
plt.grid(True)
plt.xticks(rotation=45)
plt.show()
# Apply linear interpolation
data['sales_interpolated'] = data['sales'].interpolate(method='linear')
print("\nData After Linear Interpolation:")
print(data)
# Plot the original and interpolated data
plt.figure(figsize=(10, 5))
plt.plot(data['date'], data['sales'], label='Original Sales', marker='o')
plt.plot(data['date'], data['sales_interpolated'], label='Interpolated Sales', marker='x')
plt.title('Sales Data with Linear Interpolation')
plt.xlabel('Date')
plt.ylabel('Sales')
plt.legend()
plt.grid(True)
plt.xticks(rotation=45)
plt.show()