Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python Pandas - เติมค่า NaN ด้วย Polynomial Interpolation

ใช้เมธอด interpolate() ของ Pandas Series พร้อมตั้งค่า method='polynomial' และ order (ลำดับของพหุนาม) เพื่อประมาณค่า NaN

ตัวอย่างโค้ด

import pandas as pd
import numpy as np

# pandas series with NaN
d = pd.Series([10, 20, np.nan, 65, 75, 85, np.nan, 100])
print("Series...\n", d)

# Polynomial Interpolation order 2
print("\nPolynomial Interpolation...\n", d.interpolate(method='polynomial', order=2))

ผลลัพธ์

Series...
0    10.0
1    20.0
2     NaN
3    65.0
4    75.0
5    85.0
6     NaN
7   100.0
dtype: float64

Polynomial Interpolation...
0    10.000000
1    20.000000
2    42.854015
3    65.000000
4    75.000000
5    85.000000
6    93.532847
7   100.000000
dtype: float64

คำอธิบาย

  • สร้าง Series ที่มีค่า np.nan
  • interpolate(method='polynomial', order=2) ใช้พหุนามลำดับ 2 (Quadratic) ประมาณค่า
  • เหมาะกับข้อมูลที่มีแนวโน้มโค้ง (Non-linear)
  • order ต้องน้อยกว่าจำนวนจุดข้อมูลที่ไม่ใช่ NaN