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

时间:2016-03-03 20:38:41

标签: python dataset

我有一些数据集(让我们留在这里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值(平均值)。

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

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

graph corresponding to example lists

1 个答案:

答案 0 :(得分:0)

好吧,我只是试图实现我提到的内容,它就像我喜欢它一样。 虽然我认为有些事情仍然有点笨拙......

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()
相关问题