【发布时间】:2021-08-09 16:45:44
【问题描述】:
我试图允许用户从 DataFrame 和比较运算符(>=、<= 或 ==)输入列名,并根据用户选择的运算符,将 DataFrame 值与他们选择的收盘价。 df.loc[df[column_name]] 部分和 valueofclose 部分工作正常,但是我收到一个错误:
numpy.core._exceptions.UFuncTypeError: ufunc 'add' did not contain a loop with signature matching types (dtype('float64'), dtype('<U2')) -> None
我认为问题是因为用户输入了一个字符串,我需要它成为源代码,我想到的唯一方法是在它周围使用 + 并添加 exec 函数,但这也会执行代码我不知道之后该怎么办。
valueofclose = int(input("What is your value of the percent close: "))
column_name = input("Which column would you like to focus on: Percent Gain, Percent Loss or Day % Change: ")
operator = (input("What would you like for the operator to be: >=, <= or =="))
print(type(operator))
df_loss = df.loc[df[column_name] + operator + valueofclose] #lets me find days where percent loss is greater than 4
for i, rows in df_loss.iterrows(): #Goes through the df_loss dataframe (where percent is greater than 4)
my_listloss = rows.notindex - 1 #and gets the index of that and subtracts the index by 1 to get the index of the next day
Percentloss_list.append(my_listloss) #adds that index to the list
【问题讨论】:
-
欢迎来到 Stack Overflow。如果您向我们展示实际代码,我们只能告诉您您的代码有什么问题。它不必是您的整个项目,但它确实需要是一个完整的、独立的示例,显示您所描述的问题,其他人可以复制、粘贴和运行。详情请阅读How to Ask 和stackoverflow.com/help/minimal-reproducible-example。另外,Please do not upload images of code/errors when asking a question.
-
顺便说一句,将
exec函数与用户输入的字符串一起使用几乎总是一个坏主意。用户可以想办法输入恶意代码,然后在程序内部执行。