【发布时间】:2021-08-31 21:58:24
【问题描述】:
我有一个二元分布,它是从 'Int_1','Int_2' 中每个 Group 的 xy 点生成的。我通过Norm 对分布进行归一化,并将其传递给轮廓以显示 z 值。
我想返回'Item_X','Item_Y' 中显示的 xy 点处二元分布的 z 值。下图中使用白色散点的一个示例。
最终,我会将'Item_X','Item_Y' 在每个时间点的 z 值传递给数据框,并将其附加回原始 df。
import pandas as pd
import numpy as np
from scipy.stats import multivariate_normal as mvn
import matplotlib.pyplot as plt
from scipy.interpolate import RectBivariateSpline
df = pd.DataFrame({'Int_1': [1.0, 2.0, 1.0, 3.0, 1.0, 2.0, 3.0, 2.0],
'Int_2': [1.0, 2.0, 2.0, 2.0, 1.0, 1.0, 1.0, 2.0],
'Item_X': [0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0],
'Item_Y': [0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0],
'Period': [1, 1, 1, 1, 2, 2, 2, 2],
'Group': ['A', 'B', 'A', 'B', 'A', 'B', 'A', 'B'],
'Item': ['Y', 'Y', 'A', 'B', 'A', 'B', 'A', 'B'],
'id': ['1', '2', '3', '4', '1', '2', '3', '4']})
Group_A = [df[df['Group'] == 'A'][['Int_1','Int_2']].to_numpy()]
Group_B = [df[df['Group'] == 'B'][['Int_1','Int_2']].to_numpy()]
Item = [df[['Item_X','Item_Y']].to_numpy()]
period = df['Period'].drop_duplicates().reset_index(drop = True)
def bivart_func(member_no, location, time_index, group):
if group == 'A':
data = Group_A.copy()
elif group == 'B':
data = Group_B.copy()
else:
return
if np.all(np.isfinite(data[member_no][[time_index,time_index + 1],:])) & np.all(np.isfinite(Item[0][time_index,:])):
sxy = (data[member_no][time_index + 1,:] - data[member_no][time_index,:]) / (period[time_index + 1] - period[time_index])
mu = data[member_no][time_index,:] + sxy * 0.5
out = mvn.pdf(location,mu) / mvn.pdf(data[member_no][time_index,:],mu)
else:
out = np.zeros(location.shape[0])
return out
xx,yy = np.meshgrid(np.linspace(-10,10,200),np.linspace(-10,10,200))
Z_GA = np.zeros(40000)
Z_GB = np.zeros(40000)
for k in range(1):
Z_GA += bivart_func(k,np.c_[xx.flatten(),yy.flatten()],0,'A')
Z_GB += bivart_func(k,np.c_[xx.flatten(),yy.flatten()],0,'B')
fig, ax = plt.subplots(figsize=(8,8))
ax.set_xlim(-10,10)
ax.set_ylim(-10,10)
Z_GA = Z_GA.reshape((200,200))
Z_GB = Z_GB.reshape((200,200))
Norm = xx,yy, (Z_GA - Z_GB)
cfs = ax.contourf(*Norm, cmap = 'magma')
ax.scatter(Item[0][1,0],Item[0][1,1], color = 'white', edgecolor = 'black')
f = RectBivariateSpline(xx[0, :], yy[:, 0], Norm)
z = f(df['Item_X'], df['Item_Y'], grid = False)
print(z)
【问题讨论】:
标签: python scipy interpolation distribution gaussian