给定横坐标插值获得纵坐标（包含时间序列插值）Python

1. 一般序列

import numpy as np

x = np.arange(-5, 5, 0.05)
y = np.cos(x)


https://numpy.org/doc/stable/reference/generated/numpy.interp.html

import matplotlib.pyplot as plt

plt.plot(x, y)
plt.plot(2.017, np.interp(2.017, x, y), 'r*')
plt.show()


2. 日期序列

import datetime
import numpy as np
import matplotlib.pyplot as plt

# 获得原始序列，x为日期格式
xdate = []
y = []

begin = datetime.date(2020,1,1)

# 每隔两天有一个数据，所以2020.10.02的数据是空缺的
for i in range(180):
day = begin + datetime.timedelta(days=2*i)
xdate.append(day)
y.append(np.cos(i/50 * np.pi))

# 转化为整数
xdate_int = [int(t.strftime("%Y%m%d")) for t in xdate]

# 需要插值的点
day = datetime.date(2020,10,2)
# 转化为时间整数，因为datatime没法插值
x_day_int = int(day.strftime("%Y%m%d"))
# 用np方法插值的时间获得y
xday_y = np.interp(x_day_int, xdate_int, y)

plt.plot(xdate, y)
plt.plot(day, xday_y, 'r*')


3.一般的时间序列

import datetime
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# 获得原始序列，xtimelist为一般的时间格式
xtimelist = pd.date_range('2020-01-01 00:00:00', '2020-01-01 05:00:00', freq= '1min')

y = []
for i in range(len(xtimelist)):
y.append(np.cos(i/60 * np.pi))

# 转化为整数
xtimelist_int = [np.datetime64(t).astype(np.int64) for t in xtimelist]

# 需要插值的点
x_time = np.datetime64('2020-01-01 03:21:07.000000')
# 转化为时间整数，因为datatime没法插值
x_time_int = x_time.astype(np.int64)

# 用np方法插值的时间获得y
x_time_y = np.interp(x_time_int, xtimelist_int, y)

plt.plot(xtimelist, y)
plt.plot(x_time, x_time_y, 'r*')
plt.show()


08-04 8万+

12-20 9350
04-24 1888
07-13 2014
06-25 1992
05-14 3万+
11-15 168
11-03 20万+
06-08 3391
10-25 7077
01-15 1049
01-29 2万+