【问题标题】:From a tuple list, Insert tuples Index[0] and Index[1] into a function从元组列表中,将元组 Index[0] 和 Index[1] 插入到函数中
【发布时间】:2021-12-09 06:29:33
【问题描述】:

祝大家好运,

目标是能够通过将 x 和 y 插入 df[f'sma_{x}Vs_sma{y}'] 函数来创建一系列新列。

我遇到的问题是我只将最后一个元组值放入函数中,因此进入数据框,正如您在最后一张图片上看到的那样。

在代码的第二部分,3 个示例说明了如何将元组值插入到函数中。在示例中,我将使用前 2 个元组 (10,11)、(10,12) 和最后一个元组 (48,49)

代码:

a = list(combinations(range(10, 15),2))
print(a)

for index, tuple in enumerate(a):
    x = tuple[0]
    y = tuple[1]
    print(x, y)

df[f'sma_{x}_Vs_sma_{y}'] = np.where(ta.sma(df['close'], lenght = x)  > ta.sma(df['close'], lenght = y),1,-1)

代码示例:

元组 (10,11)

df[f'sma_{10}_Vs_sma_{11}'] = np.where(ta.sma(df['close'], lenght = 10)  > ta.sma(df['close'], lenght = 11),1,-1)

元组 (10,12)

df[f'sma_{10}_Vs_sma_{12}'] = np.where(ta.sma(df['close'], lenght = 10)  > ta.sma(df['close'], lenght = 12),1,-1)

元组 (13,14)

df[f'sma_{13}_Vs_sma_{14}'] = np.where(ta.sma(df['close'], lenght = 13)  > ta.sma(df['close'], lenght = 14),1,-1)

Error code

【问题讨论】:

  • 作为一般规则,如果您的编辑器将您的变量名设置为与其他变量名不同的颜色,则选择的变量名可能会给您一些奇怪的行为,因为它已经在使用中。我会在你的 for 循环中更改 tuple 的名称。它可能与您的问题无关,但如果您使用tup 或其他东西,它会更安全。 tuple 也是用于创建元组的内置函数的名称。
  • 非常感谢你的 cmets,如果你能给我一个简单的例子,我真的很感激,我是 python 新手,这个问题需要很多时间。

标签: python function tuples iteration


【解决方案1】:

下一行是解决问题的代码。虽然向后看接缝很容易,但我花了一些时间才找到答案。

感谢对此问题发表评论的人

a = list(combinations(range(5, 51),2))
print(a)

for x, y in a :
  df[f'hma_{x}_Vs_hma_{y}'] = np.where(ta.hma(df['close'], lenght = x)  > ta.hma(df['close'], lenght = y),1,-1)

【讨论】:

    猜你喜欢
    • 2021-05-04
    • 2021-11-02
    • 1970-01-01
    • 2019-09-08
    • 1970-01-01
    • 2017-10-05
    • 2019-08-12
    • 2018-07-31
    • 1970-01-01
    相关资源
    最近更新 更多