gpt4 book ai didi

python for循环作为函数中的elif语句

转载 作者:行者123 更新时间:2023-12-01 00:41:17 25 4
gpt4 key购买 nike

我试图在循环列表中的值的函数内插入一个 for 循环。

假设我有以下数据框:

import pandas as pd

df = pd.DataFrame()

df['A'] = (53.104898, 52.032832, 48.705107, 43.150132, 42.09353, 42.32076, 41.620527, 44.479339, 44.673272, 43.811447, 44.273042, 47.384234, 49.210512, 50.330492 ,48.808856, 49.543268, 43.460175, 41.54373, 49.618678, 44.988629, 52.964725,
56.358917, 53.366254)
df['B'] = (2.157,2.0826,0.8452,-0.3046,-0.3436,-0.3906,-1.1528,-0.9462,-1.1314,-0.9994,-1.0538,0.785,1.5334,0.1424, 0.764,-0.6844,-2.5798,-2.3644,-1.97,-3.7466,-1.862,-0.248, -0.456)

def func():
q = [40,60]

def valuation_formula(x, y):

for i in q:
if x > 3.9:
return 'SIT'
elif x < -3.8:
return 'SIT'
elif x > 0.00 and y > i:
return 'BUY'
elif x < 0.00 and y < 41.14:
return 'SELL'
else:
return 'SIT'

df['C'] = df.apply(lambda row: valuation_formula(row['A'], row['B']), axis=1)

print(df)
i=i+1

func()

实际结果应该是 2 个独立的数据帧。 1 个数据帧使用 40 作为列表 q 中的 i,第二个数据帧使用 60

最佳答案

正如评论中提到的,循环内的 return 将终止所有内容,因此您只会查看 q 的第一个值。另外,您正在混合 for i in qi+=1...

无论如何,快速解决方法是:

q = [40,60]

def valuation_formula(i, x, y):
# pass the i as a parameter
if x > 3.9:
return 'SIT'
elif x < -3.8:
return 'SIT'
elif x > 0.00 and y > i:
return 'BUY'
elif x < 0.00 and y < 41.14:
return 'SELL'
else:
return 'SIT'

# loop here
for i in q:
df['C'] = df.apply(lambda row: valuation_formula(i, row['A'], row['B']), axis=1)
print(df)

关于python for循环作为函数中的elif语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57326799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com