Interpolation of arrays in Python
This program is made to read an array and interpolate any value in column and provide corresponding value in another column in same row. Written as Python module for easy and global implementation.
import pandas as pd
import numpy as np
"""final updated Python module that:
✅ Works with both column names and indices
✅ Handles both pandas DataFrames and NumPy arrays
✅ Returns the matching or interpolated value
✅ Also returns the row index used (for exact match or lower bounding index in interpolation)
✅ Includes error handling and comments
✅ USE ZERO BASED INDEX IN FUNCTION"""
def find_or_interpolate(df_or_array, search_col, val, target_col):
"""
Search for or interpolate a value in a DataFrame or 2D NumPy array.
Parameters:
- df_or_array: pandas DataFrame or 2D numpy array
- search_col: int or str — column index or name to search in
- val: numeric — value to find or interpolate
- target_col: int or str — column index or name to retrieve from
Returns:
- (val, result, row_index):
- val: the input value
- result: exact or interpolated value from target_col
- row_index:
- index of row if exact match
- lower bound index if interpolated
- None if out of bounds or error
"""
# Convert to DataFrame if input is a NumPy array
if isinstance(df_or_array, np.ndarray):
df = pd.DataFrame(df_or_array)
else:
df = df_or_array.copy()
# Clean up column names (remove extra spaces/newlines)
df.columns = df.columns.astype(str).str.strip()
try:
search_col_idx = df.columns.get_loc(search_col) if isinstance(search_col, str) else search_col
target_col_idx = df.columns.get_loc(target_col) if isinstance(target_col, str) else target_col
except (KeyError, IndexError):
print(f"Invalid column: '{search_col}' or '{target_col}'")
return None, None, None
# Column index bounds check
if not (0 <= search_col_idx < df.shape[1]) or not (0 <= target_col_idx < df.shape[1]):
print(f"Error: Column index out of range. Data has {df.shape[1]} columns.")
return None, None, None
# Sort DataFrame by the search column
df = df.iloc[df.iloc[:, search_col_idx].argsort()].reset_index(drop=True)
x = df.iloc[:, search_col_idx].to_numpy()
y = df.iloc[:, target_col_idx].to_numpy()
# Exact match
if val in x:
idx = int(np.where(x == val)[0][0])
return val, y[idx], idx
# Out of bounds
if val < x[0] or val > x[-1]:
print(f"Value {val} is out of bounds: ({x[0]} to {x[-1]})")
return None, None, None
# Interpolation
idx = np.searchsorted(x, val)
x0, x1 = x[idx - 1], x[idx]
y0, y1 = y[idx - 1], y[idx]
interpolated = y0 + (val - x0) * (y1 - y0) / (x1 - x0)
return val, interpolated, idx - 1 # Return index of the lower bounding row
#USAGE
"""
import pandas as pd
from interpolation_utils import find_or_interpolate
# Load your data (with headers)
df = pd.read_csv('data.csv')
# Clean column names in case of extra spaces
df.columns = df.columns.str.strip()
# Add headers manually if not in original file
df.columns = ['num', 'square', 'cube', 'new_column'] #Add manual headers
# Test exact match
val, result, row = find_or_interpolate(df, search_col='num', val=5, target_col='cube')
print(f"Exact match → Value: {val}, Result: {result}, Row index: {row}")
# Test interpolation
val, result, row = find_or_interpolate(df, search_col='num', val=6.5, target_col='cube')
print(f"Interpolated → Value: {val}, Result: {result}, Used row index: {row}")
# Test interpolation with column number instead of header
val, result, row = find_or_interpolate(df, search_col=0, val=6.5, target_col='cube')
print(f"Interpolated → Value: {val}, Result: {result}, Used row index: {row}")
"""
# COMMENTS
"""
[1] Add ----from interpolation_utils3 import find_or_interpolate--- in the executing file.
[2] Usage
# Use 0 based indices here.
data.txt looks like this. It should preferably with header.
If no header set header as
num,square,cube
1,1,1
2,4,8
3,9,27
4,16,64
5,25,125
6,36,216
7,49,343
8,64,512
10,100,1000
df looks like this :
num square cube new_column
0 1 1 1 5
1 2 4 8 28
2 3 9 27 87
3 4 16 64 200
4 5 25 125 385
5 6 36 216 660
6 7 49 343 1043
7 8 64 512 1552
8 10 100 1000 3020
9 22 92 472 1460
10 32 192 1472 4480
11 54 284 1944 5940
12 86 476 3416 10420
13 140 760 5360 16360
14 226 1236 8776 26780
Handle headers in CSV file
CSV with headers df = pd.read_csv('file.csv') (default)
CSV without headers df = pd.read_csv('file.csv', header=None)
NumPy array Use as-is — column indices only
Handling of headers
Since the function uses .iloc and integer indices, it ignores column names.
So it works fine whether or not the DataFrame has headers, as long as you pass correct column indices.
"""
# return values
"""
(val, result, row_index) val, res, row_idx = ...
If you only want result Use _ , res, _ = ...
If you want everything Use all three variables
"""