Python-“无法使用灵活类型执行归约"尝试使用numpy.mean时 [英] Python - "cannot perform reduce with flexible type" when trying to use numpy.mean

查看:251
本文介绍了Python-“无法使用灵活类型执行归约"尝试使用numpy.mean时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我精疲力尽,因为当我尝试计算列的平均值时,我不断收到无法使用弹性类型执行归约"的操作,文件读取得很好(任何行/列中都没有缺失值)但是当我加入以下内容时: Brain_wt_mean = np.mean(ifile axis = 0),那么Python 2.7.5不喜欢它.我在Spyder IDE中使用它.非常感谢您的帮助.

I'm at my wit's end as I keep getting "cannot perform reduce with flexible type" when I try to compute the mean of a column, the file is read in just fine (no missing values in any rows/column) but when I put in the line: Brain_wt_mean = np.mean(ifile axis=0) then Python 2.7.5 does not like it. I am using this within the Spyder IDE. Thanks much for any help.

import os
import numpy as np

if __name__ == "__main__":
    try:        
        curr_dir = os.getcwd()
        file_path = curr_dir + '\\brainandbody.csv'
        ifile = np.loadtxt('brainandbody.csv', delimiter=',', skiprows=1, dtype=[('brainwt', 'f8'), ('bodywt', 'f8')])

    except IOError:
        print "The file does not exist, exiting gracefully"        

Brain_wt_mean = np.mean(ifile axis=0)




### BELOW is a sample of the csv file ######

Brain Weight    Body Weight
3.385   44.5
0.48    15.5
1.35    8.1
465 423
36.33   119.5
27.66   115
14.83   98.2
1.04    5.5

推荐答案

在使用结构化数组时,您将失去原本会拥有的一些灵活性.不过,您可以在选择适当的片段后取均值:

When you're working with structured arrays like that you lose some of the flexibility you'd otherwise have. You can take the mean after selecting the appropriate piece, though:

>>> ifile
array([(3.385, 44.5), (0.48, 15.5), (1.35, 8.1), (465.0, 423.0),
       (36.33, 119.5), (27.66, 115.0), (14.83, 98.2), (1.04, 5.5)], 
      dtype=[('brainwt', '<f8'), ('bodywt', '<f8')])
>>> ifile["brainwt"].mean()
68.759375000000006
>>> ifile["bodywt"].mean()
103.66249999999999


我几乎每天都使用numpy,但是在处理我想为列命名的数据时,我认为 pandas 库使事情变得更加方便,并且可以很好地互操作.值得一看.示例:


I use numpy almost every day, but when working with data of the sort where I want to name columns, I think the pandas library makes things much more convenient, and it interoperates very well. It's worth a look. Example:

>>> import pandas as pd
>>> df = pd.read_csv("brainandbody.csv", skipinitialspace=True)
>>> df
   Brain Weight  Body Weight
0         3.385         44.5
1         0.480         15.5
2         1.350          8.1
3       465.000        423.0
4        36.330        119.5
5        27.660        115.0
6        14.830         98.2
7         1.040          5.5
>>> df.mean()
Brain Weight     68.759375
Body Weight     103.662500
dtype: float64

这篇关于Python-“无法使用灵活类型执行归约"尝试使用numpy.mean时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆