python - 取 'error cannot perform reduce with flexible type' python中读取的数据的平均值

标签 python numpy mean

我试图从文本文件中读取数据并取该数据的平均值,但出现错误无法使用灵活类型执行reduce。我不知道为什么,有人可以帮忙吗?这是我的代码。

right=open('01phi.txt','r').readlines()  
right=str(right) 
a=np.asarray(right)
b=np.mean(a)
print b

编辑:我现在正在使用这条线 right=np.genfromtxt('01phi.txt') 但它会产生此错误 Line #10 (got 3 columns而不是 7) 因为数组中的这一行没有那么大。 Using genfromtxt to import csv data with missing values in numpy这个链接告诉我如何忽略底线或如何填写它,但这两种方法都会挤压平均值。有办法解决这个问题吗?

最佳答案

right 是一个字符串。 np.asarray(some_string) 返回一个字符串数据类型的数组。 NumPy 的 np.mean 函数在传递字符串 dtype 数组时会引发 TypeError。

In [29]: np.asarray('1 2 3')
Out[29]: 
array('1 2 3', 
      dtype='|S5')
In [31]: np.mean(a)
TypeError: cannot perform reduce with flexible type

相反,请使用 np.genfromtxtnp.loadtxt从文本文件加载数组:

a = np.genfromtxt(filename, ...)

关于python - 取 'error cannot perform reduce with flexible type' python中读取的数据的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17277750/

相关文章:

r - 如何在 ggplot2 R 中的轴上绘制均值和误差条

c++ - 有没有比生成/累积更快的方法来计算函数结果的平均值?

python - 使用 Scipy 与 ROOT 等拟合(高斯)

python - Cron 作业正在将错误写入错误日志,但无法将输出写入输出日志文件

Python list.insert() 多索引/列表列表

python - 计算包含 None 类型的列表的均值和最小值

python,可能是马尔可夫链的变体?

Python Pandas 基于列相乘并添加后缀

python - 如何增加日期类型的索引

python - (Python) 如何在不执行 A*B 的情况下获得对角线 (A*B)?