繁体   English   中英

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值(平均值)。

有没有一种简单的已知方法可以实现这一目标(也许是熊猫)? 我的第一个猜测是找到某个X1值的所有t值(在本示例中,X1值10处于2,...,7范围内),然后在该值中查找所有X2值范围并获取其平均值。 然后,您应该可以分配YNew(XNew)。 感谢您的每条建议!

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

与示例列表相对应的图形

好吧,我只是尝试实现我提到的内容,并且按我喜欢的方式工作。 尽管我认为有些事情仍然有些笨拙...

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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM