ako*_*ako 5 python numpy scipy pandas
我在熊猫数据框中有许多系列,代表每年观察到的费率.
对于一个实验,我希望这些系列中的一些系列的费率能够在最后一年中收敛到其他系列的费率之一.
例如,假设我有这些数据,并且我认为列a是一个有意义的目标,使得列b渐近地接近,例如,以小的,甚至大小的增量(或减少;并不重要)的十年期间.
我当然可以在一个循环中这样做,但我想知道是否有一种更通用numpy或scipy矢量化的方式使一个系列方法另一个渐近地下架.
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
Run Code Online (Sandbox Code Playgroud)
一般来说,你会在某个范围内应用"缓动功能".
例如,请考虑下图:
在这里,我们有两个原始数据集.我们将减去两者,将差值乘以第三行中显示的缓动函数,然后将结果添加回第一条曲线.这将导致一个新系列,即灰色区域左侧的原始数据,灰色区域内两者的混合,以及灰色区域右侧的另一条曲线的数据.
举个例子:
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
Run Code Online (Sandbox Code Playgroud)
另外,如果你对上面的情节感到好奇,这里是它的生成方式:
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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
447 次 |
| 最近记录: |