gpt4 book ai didi

python - 如何消除 "unsupported operand type(s) for -: ' str' 和 'str' "错误如下?

转载 作者:行者123 更新时间:2023-12-01 00:09:29 26 4
gpt4 key购买 nike

当我运行以下代码时,

def difference(dataset, interval=1):
diff = list()
for i in range(interval, len(dataset)):
value = dataset[i] - dataset[i - interval]
diff.append(value)
return numpy.array(diff)

series = read_csv('Houston_weather.csv', header=None)
X = series.values
days_in_year = 365
differenced = difference(X, days_in_year)

我收到以下错误,有办法消除它吗?我正在研究天气的时间序列。

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-70-a0a67d687691> in <module>
4 X = series.values
5 days_in_year = 365
----> 6 differenced = difference(X, days_in_year)

<ipython-input-64-b7e841922d29> in difference(dataset, interval)
3 diff = list()
4 for i in range(interval, len(dataset)):
----> 5 value = dataset[i] - dataset[i - interval]
6 diff.append(value)
7 return numpy.array(diff)

TypeError: unsupported operand type(s) for -: 'str' and 'str'

我的数据框是: enter image description here

最佳答案

它只是说“您正在尝试在 2 个字符串之间使用 - 运算符”。您应该将它们转换为数字。

value = int(dataset[i]) - int(dataset[i -interval]) 如果它们是整数,可能会有所帮助。

value = float(dataset[i]) - float(dataset[i -interval]) 如果它们是 float ,可能会有所帮助。

此外,pandas 的文档说最好使用 to_numpy() 而不是 values

Warning We recommend using DataFrame.to_numpy() instead.

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.values.html

关于python - 如何消除 "unsupported operand type(s) for -: ' str' 和 'str' "错误如下?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59728678/

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