python - NumPy 的/科学的 : Making one series converge towards another after a period of time

标签 python numpy pandas scipy

我在 pandas 数据框中有许多系列代表每年观察到的比率。

对于实验,我希望这些系列中的某些系列的比率在最后观察的一年中收敛到其他系列中的一个。

例如,假设我有这些数据,并且我决定 a 列是 b 列的一个有意义的目标,以渐近方式接近,比如说,在 10 年的时间段内小的,甚至大小的增量(或减少;并不重要)。

我当然可以在循环中执行此操作,但我想知道是否有更通用的 numpyscipy 向量化方法使一个系列接近另一个渐近关闭架子。

rate               a         b                  
year                                                                       
2006               0.393620  0.260998          
2007               0.408620  0.260527
2008               0.396732  0.257396 
2009               0.418029  0.249123 
2010               0.414246  0.253526  
2011               0.415873  0.256586  
2012               0.414616  0.253865     
2013               0.408332  0.257504    
2014               0.401821  0.259208  

最佳答案

一般来说,您会在某个范围内应用“缓动函数”。

例如,考虑下图:

enter image description here

在这里,我们有两个原始数据集。我们将两者相减,将差值乘以第三行所示的缓动函数,然后将结果加回第一条曲线。这将产生一个新系列,即灰色区域左侧的原始数据、灰色区域内两者的混合以及灰色区域右侧的另一条曲线的数据。

举个例子:

import numpy as np
import matplotlib.pyplot as plt

# Generate some interesting random data
np.random.seed(1)
series1 = np.random.normal(0, 1, 1000).cumsum() + 20
series2 = np.random.normal(0, 1, 1000).cumsum()
# Our x-coordinates
index = np.arange(series1.size)

# Boundaries of the gray "easing region"
i0, i1 = 300, 700    

# In this case, I've chosen a sinusoidal easing function...
x = np.pi * (index - i0) / (i1 - i0)
easing = 0.5 * np.cos(x) + 0.5

# To the left of the gray region, easing should be 1 (all series2)
easing[index < i0] = 1

# To the right, it should be 0 (all series1)
easing[index >= i1] = 0

# Now let's calculate the new series that will slowly approach the first
# We'll operate on the difference and then add series1 back in 
diff = series2 - series1
series3 = easing * diff + series1

此外,如果您对上面的图感到好奇,请查看它的生成方式:

fig, axes = plt.subplots(nrows=4, sharex=True)

axes[0].plot(series1, color='lightblue', lw=2)
axes[0].plot(series2, color='salmon', lw=1.5)
axes[0].set(ylabel='Original Series')

axes[1].plot(diff, color='gray')
axes[1].set(ylabel='Difference')

axes[2].plot(easing, color='black', lw=2)
axes[2].margins(y=0.1)
axes[2].set(ylabel='Easing')

axes[3].plot(series1, color='lightblue', lw=2)
axes[3].plot(series3, color='salmon', ls='--', lw=2, dashes=(12,20))
axes[3].set(ylabel='Modified Series')

for ax in axes:
    ax.locator_params(axis='y', nbins=4)
for ax in axes[-2:]:
    ax.axvspan(i0, i1, color='0.8', alpha=0.5)

plt.show()

关于python - NumPy 的/科学的 : Making one series converge towards another after a period of time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34141798/

相关文章:

python - Spotipy 不通过 Oauth 验证?

python - 不从文件加载 python 模块

python - 如何在Python中将简单列表转换为数据框

python - numpy 中的特定张量积

python - Pandas 从字典映射到 DataFrame

python - 如何从Excel获取字典的多个键和单个值

python - 3D CNN 在图像序列上的输入形状应该是什么?

javascript - 数组索引选择类似于 numpy 但在 javascript 中

python - numpy数组的快速条件重叠窗口(框架)

python - 删除 pandas 系列中仅是标点符号的单词