我想先看看我的CSV档案。https://github.com/hamzaal014/file/blob/main/file.csv
.csv文件包含两列X和Y。以下是我的脚本:
import numpy as np
from pandas import DataFrame as df
import csv
origin_data = open("file.csv", "r")
dato = list(csv.reader(origin_data, delimiter=","))
print(dato)
rowcount = 0
# iterating through the whole file
for row in dato:
rowcount+= 1
# printing the result
# _ print("Number of lines present:-", rowcount)
print(rowcount)
dati = df(dato, columns=['x', 'y'])
window = 6
roll_avg = dati.rolling(window).mean()
roll_avg_cumulative = dati['y'].cumsum()/np.arange(1, 25)
print(roll_avg_cumulative)
但我的剧本不起作用了?
错误------------------
Traceback (most recent call last):
File "/home/haz/miniconda39/lib/python3.9/site-packages/pandas/core/ops/array_ops.py", line 163, in _na_arithmetic_op
result = func(left, right)
File "/home/haz/miniconda39/lib/python3.9/site-packages/pandas/core/computation/expressions.py", line 239, in evaluate
return _evaluate(op, op_str, a, b) # type: ignore[misc]
File "/home/haz/miniconda39/lib/python3.9/site-packages/pandas/core/computation/expressions.py", line 128, in _evaluate_numexpr
result = _evaluate_standard(op, op_str, a, b)
File "/home/haz/miniconda39/lib/python3.9/site-packages/pandas/core/computation/expressions.py", line 69, in _evaluate_standard
return op(a, b)
TypeError: unsupported operand type(s) for /: 'str' and 'int'
2条答案
按热度按时间dxxyhpgq1#
当从文件中读取时,返回的是字符串。这就是问题的根源,因为字符串永远不会转换成数字。您可以通过以下方式进行修复:
如果它对您有帮助,我还想指出一些可以改进您的代码的事情:
pandas.read_csv
)len
运算符可以轻松计算行数,而无需迭代所有行import pandas as pd
),而不是创建自己的别名。这将帮助您的代码对其他人更具可读性因此,您的代码可以变成:
brtdzjyr2#
您的代码出了什么问题:
str
。简单方法