【问题标题】:taking mean of data read in 'error cannot perform reduce with flexible type' python取“错误不能使用灵活类型”python 中读取的数据的平均值
【发布时间】:2013-06-21 02:15:33
【问题描述】:

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

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

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

【问题讨论】:

    标签: python numpy mean


    【解决方案1】:

    right 是一个字符串。 np.asarray(some_string) 返回具有字符串 dtype 的数组。 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, ...)
    

    【讨论】:

    • 是的,这应该对我有用,但是当我使用 genfromtxt 时出现错误,它显示第 12 行(得到 2 列而不是 5 列),因为我的文本文件底行中的数字较少。但我只想将所有数字导入到一个数组中。我不知道如何解决这个问题
    • 这告诉我如何忽略底部值或填充缺失值stackoverflow.com/questions/3761103/… 但它很重要我不这样做,因为这会挤压平均值。有没有办法解决这个问题?
    • 有一种方法可以传递custom file-like objects to np.genfromtxt。您可以使用类似的东西来处理短行并返回完整行。但是,我认为这比您真正想要在这里使用的代码要多。我认为编写一个预处理脚本会更容易,它将旧数据文件(通过在缺失的列中添加零)重写为 np.genfromtxt 可以读取的文件。
    猜你喜欢
    • 1970-01-01
    • 2017-09-04
    • 2015-09-12
    • 2014-07-30
    • 1970-01-01
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多