小编cmp*_*cmp的帖子

构建用于平滑序列的 Factory/Builder 类模式的 Pythonic 方法

我有许多课程对一系列价格实施平滑技术。

我试图找出在__call__另一个类的函数中实现任何这些平滑类的最佳方法,然后对平滑后的序列执行一些操作:

IE

class NoSmoother:
    def __init__(self, prices):
        self.prices = prices
    
    def __call__(self):
        return self.prices

class MASmoother:
    def __init__(self, prices):
        self.prices = prices
    
    def __call__(self, window):
        return self.prices.rolling(window).mean().to_frame("price")


class ThatDoesSomethingWithSmoothedPrices():
    def __init__(self, prices):
        self.prices = prices

    def __call__(self, smoother=ma_smoother, window=3)
        smoothed_prices = SomeBuilderClassThatCallsTheCorrectSmootherClass()
Run Code Online (Sandbox Code Playgroud)

如您所见,我需要工厂/构建器类来实现NoSmoother,否则,它将调用适当的平滑类。当然,返回的对象可以从简单到复杂各不相同,例如,如果我使用卡尔曼滤波器平滑价格,则该类可以期望更多参数。

目前,我的代码class ThatDoesSomethingWithSmoothedPrices()使用价格系列进行实例化,然后通过传递 **config 进行调用。

期望的输出:

理想情况下,我希望能够从调用函数中调用任何平滑类

class ThatDoesSomethingWithSmoothedPrices()

实施示例:

configs = {'smoother': MASmoother, 'window': 3}

processor = ThatDoesSomethingWithSmoothedPrices(prices)

output = processor(**config)
Run Code Online (Sandbox Code Playgroud)

我的尝试:

class Smoother:
    def __init__(self, prices):
        self.prices = …
Run Code Online (Sandbox Code Playgroud)

python factory-pattern

6
推荐指数
1
解决办法
1471
查看次数

循环内绘制的子图图表非常挤压

我有一个包含约 120 个功能的数据框,我想按年检查这些功能。我正在循环内绘制每个特征,x =年份,y =特征值。虽然这些绘图成功,但图表由于完全被压扁而难以辨认。

我尝试过使用 plt.tight_layout() 并使用 plt.rcParams['figure.figsize'] 调整图形大小,但遗憾的是没有效果

for i in range(len(roll_df.columns)):
  plt.subplot(len(roll_df.columns), 1, i+1)
  name = roll_df.columns[i]
  plt.plot(roll_df[name])
  plt.title(name, y=0)
  plt.yticks([])
  plt.xticks([])
  plt.tight_layout()
  plt.show()
Run Code Online (Sandbox Code Playgroud)

循环运行,但所有绘图在 y 轴上都被挤压得难以辨认:

阴谋

python matplotlib seaborn

2
推荐指数
1
解决办法
2882
查看次数

标签 统计

python ×2

factory-pattern ×1

matplotlib ×1

seaborn ×1