【问题标题】:Python 2.7, np.asarray, TypeError: cannot perform reduce with flexible typePython 2.7,np.asarray,TypeError:无法使用灵活类型执行 reduce
【发布时间】:2016-09-13 19:40:41
【问题描述】:

我有一个包含 390 行和大约 8000 列的 .txt 文件。数据仅包含由空格分隔的 1 和 0。我想计算所有列中数字 1 出现在每列(每列总和)中的次数。我为此使用 numpy 数组。问题是我在脚本行“b = a.sum(axis=0)”中不断收到以下错误消息:

"TypeError: 不能使用灵活类型执行 reduce"

欢迎提出任何建议!

这是我正在使用的简单代码:

import csv
import numpy as np
from numpy import genfromtxt
my_data = genfromtxt('test1.txt', dtype='S', delimiter=',') 
a = np.asarray(my_data)

import sys  
sys.stdout = open("test1.csv", "w") 

b = a.sum(axis=0)
print b

输入示例,test1.txt:

1 0 0 0 1 1 0 1 
0 1 1 0 1 1 1 1 
1 0 0 0 0 1 0 0
0 1 1 0 1 0 1 1

预期输出:

2 2 2 0 3 3 2 3

【问题讨论】:

  • 第一步是正确使用genfromtxt。你打印了a 还是查看了它的属性?或者看看my_data

标签: numpy multidimensional-array


【解决方案1】:

您收到该错误是因为您正在使用 dtype='S' 导入数据,这是一个字符串。您必须使用正确的dtype 导入数据,例如int

您不需要导入csv,也不需要使用np.asarray。只需使用np.genfromtxtdelimiter=' 'dtype=int 打开文件。

试试:

import numpy as np

my_data = np.genfromtxt('test1.txt', dtype=int, delimiter=' ')
b = my_data.sum(axis=0)

【讨论】:

  • 优秀!!。非常感谢@Francesco Nazzaro!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-12
  • 2014-02-23
  • 2013-12-02
  • 2015-04-08
  • 2020-10-08
  • 2020-10-03
  • 2015-09-12
相关资源
最近更新 更多