【问题标题】:how to run certain function until we got desired values, python如何运行某些函数,直到我们得到所需的值,python
【发布时间】:2018-05-14 09:29:56
【问题描述】:

我有一个 for 循环,通过它我可以为每个月生成一些随机的每日值。我需要确保生成的每月平均值应等于观察到的平均值(在不同的数据框中提供)。所以我需要运行这个 for 循环,直到生成所需的值,然后再运行下个月。

我有示例代码,但不确定如何多次运行它直到获得所需的值:

for j in np.arange(1,13,1):
    # calculating monthly leanth from provided datasets 
    mlen = ((df_test[df_test.index.year==2000]).index.month==j).sum()

    # fit to my distribution
    phat = stats.exponweib.fit((df_test[df_test.index.month==j].mean(axis=1)).dropna())

    # predicting based on the fitted distribution
    esti = stats.exponweib.rvs(*phat,int(mlen))

    if esti.mean() == monthly_mean[0]

monthly_mean 是观察到的每月平均值,如下所示,其中第一个月的第一个值。

monthly_mean = array([  5.15    ,   5.948571,   7.028261,   4.144231,   3.585965,
         5.244828,   4.915455,   4.757   ,   5.803614,  12.573684,
         5.683333,   3.875   ])

非常感谢任何帮助/建议!

【问题讨论】:

  • 你应该使用while循环
  • @Dipu 或 1 个 for 循环
  • @Dipu 代替 if 或代替 for 循环?

标签: python-3.x numpy for-loop if-statement


【解决方案1】:

您可以使用标志来检查何时必须停止搜索

flag = True
while (flag):
    for j in np.arange(1,13,1):
        # calculating monthly leanth from provided datasets 
        mlen = ((df_test[df_test.index.year==2000]).index.month==j).sum()

        # fit to my distribution
        phat = stats.exponweib.fit((df_test[df_test.index.month==j].mean(axis=1)).dropna())

        # predicting based on the fitted distribution
        esti = stats.exponweib.rvs(*phat,int(mlen))

        if esti.mean() == monthly_mean[0]:
            flag = False

由于您需要每月检查一次,因此可以将 if 嵌入到 for 循环中

for month_thingy in monthly_mean:
    if esti.mean() == month_thingy:
        flag = False

【讨论】:

  • bool flag = true ^ SyntaxError: invalid syntax
  • 我担心我可能错了..它似乎只比较第一个月。我在想当它在第一个月得到最佳匹配时,它应该在第二个月生成,所以我将拥有一年的完整数据集
  • 你可以在for循环中嵌入最后一个条件,我会编辑给你一个例子
  • 谢谢@Cid,感谢您的帮助:)
  • 不客气,代码可以升级,避免无用的迭代,让它更pythonic
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-30
  • 2021-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多