Python 合并数据集 X1(t), X2(t) -> X1(X2)

Python merge datasets X1(t), X2(t) -> X1(X2)

我有一些数据集(让我们在这里保持 2)依赖于一个公共变量 t,比如 X1(t) 和 X2(t)。但是 X1(t) 和 X2(t) 不必共享相同的 t 值,甚至不必具有相同数量的数据点。

例如,它们可能看起来像:

t1 = [2,6,7,8,10,13,14,16,17]
X1 = [10,10,10,20,20,20,30,30,30]

t2 = [3,4,5,6,8,10,11,14,15,16]
X2 = [95,100,100,105,158,150,142,196,200,204]

我正在尝试创建一个新数据集 YNew(XNew) (=X2(X1)),以便两个数据集在没有共享变量 t 的情况下链接。 在这种情况下,它应该看起来像:

XNew = [10,20,30]
YNew = [100,150,200]

为每个出现的 X1 值分配相应的 X2 值(平均值)。

是否有一种已知的简单方法来实现此目的(可能使用 pandas)? 我的第一个猜测是找到某个 X1 值的所有 t 值(在示例中,X1 值 10 将位于 2,...,7 范围内),然后在其中查找所有 X2 值范围并得到它们的平均值。然后你应该能够分配 YNew(XNew)。 谢谢大家的建议!

更新: 我添加了一个图表,所以也许我的意图更清楚一些。我想将平均 X2 值分配给标记区域(出现相同 X1 值的地方)中相应的 X1 值。

graph corresponding to example lists

好吧,我只是尝试实现我提到的内容,并且效果如我所愿。 虽然我觉得有些东西还是有点笨拙...

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

# datasets to treat
t1 = [2,6,7,8,10,13,14,16,17]
X1 = [10,10,10,20,20,20,30,30,30]

t2 = [3,4,5,6,8,10,11,14,15,16]
X2 = [95,100,100,105,158,150,142,196,200,204]

X1Series = pd.Series(X1, index = t1)
X2Series = pd.Series(X2, index = t2)

X1Values = X1Series.drop_duplicates().values #returns all occuring values of X1 without duplicates as array

# lists for results
XNew = []
YNew = []

#find for every occuring value X1 the mean value of X2 in the range of X1
for value in X1Values:
    indexpos = X1Series[X1Series == value].index.values
    max_t = indexpos[indexpos.argmax()] # get max and min index of the range of X1
    min_t =indexpos[indexpos.argmin()]
    print("X1 = "+str(value)+" occurs in range from "+str(min_t)+" to "+str(max_t))
    slicedX2 = X2Series[(X2Series.index >= min_t) & (X2Series.index <= max_t)] # select range of X2
    print("in this range there are following values of X2:")
    print(slicedX2)
    mean = slicedX2.mean() #calculate mean value of selection and append extracted values
    print("with the mean value of: " + str(mean))
    XNew.append(value)
    YNew.append(mean)

fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)

ax1.plot(t1, X1,'ro-',label='X1(t)')
ax1.plot(t2, X2,'bo',label='X2(t)')
ax1.legend(loc=2)
ax1.set_xlabel('t')
ax1.set_ylabel('X1/X2')

ax2.plot(XNew,YNew,'ro-',label='YNew(XNew)')
ax2.legend(loc=2)
ax2.set_xlabel('XNew')
ax2.set_ylabel('YNew')
plt.show()