【问题标题】:Python comparison operators of wrong data type错误数据类型的 Python 比较运算符
【发布时间】: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

【问题讨论】:

标签: python string dataframe


【解决方案1】:

我希望这个解决方案对您有所帮助:

def add_op(a, b):
    return a + b

def power_op(a, b):
    return pow(a, b)

operation_dict = {
    '+': add_op,
    'power': power_op,
}

a, op, b = input("Enter command: ").split()
print(operation_dict[op](int(a), int(b)))
Enter command: 3 + 3
6

Enter command: 3 power 3
27

或者,在更简单的代码中使用lambda

operation_dict = {
    '+': lambda a, b: a + b,
    'power': lambda a, b: pow(a, b),
}

a, op, b = input("Enter command: ").split()
print(operation_dict[op](int(a), int(b)))

【讨论】:

  • 请考虑在代码中添加 cmets 和解释。
猜你喜欢
  • 2010-12-16
  • 1970-01-01
  • 2021-11-07
  • 1970-01-01
  • 1970-01-01
  • 2011-02-03
  • 1970-01-01
  • 2019-03-20
  • 2018-11-29
相关资源
最近更新 更多