计算平均值& var numpy genfromtxt dataframe - TypeError ufunc add

时间:2017-06-11 19:27:00

标签: python numpy typeerror numpy-ufunc

我有包含浮点数的简单文本文件,例如:

3.235235
0.2346236
1.235235

我试图计算平均值&使用以下代码的每个文件的差异:

import numpy
import os

def main():
    for filename in os.listdir("./"):
        try:
            df = numpy.genfromtxt(filename, delimiter='\n', usecols=(0))
            with open(filename, "a") as newfile:
                newfile.write("\nMean: " + numpy.mean(df) + "\n")
                newfile.write("\Variance: " + numpy.var(df) + "\n")
                newfile.close()

        except IOError:
            print "Error reading file: %r\n" % filename

        except ValueError:
            print "Non-numeric data found in the file: %r\n" % filename         

if __name__ == "__main__":
    main()

但是我收到以下错误:

newfile.write("\nMean: " + numpy.mean(df) + "\n")
TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('S32') dtype('S32') dtype('S32')

观察df看起来像:

df.dtype = float64
df.shape = (3577,)

此外,当使用python cli并运行时:

df = numpy.genfromtxt("arp_40000_host_0.txt", delimiter='\n', usecols=(0))
numpy.mean(df)

我没有错误,所以似乎问题是write回到文件?

我做错了什么?

由于

1 个答案:

答案 0 :(得分:0)

问题是来自numpy.mean()的结果,numpy.var()无法连接到字符串。

str()包裹结果解决了它。