python - 将数组与标量 : TypeError: invalid type promotion 相乘

标签 python numpy genfromtxt structured-array

我试图将 ndarray 中的每一列乘以一个标量。当我尝试执行此操作时,收到错误 TypeError: invalid type Promotion

我尝试使用array.astype(float),但这给出了所有NaN

array = np.genfromtxt("file.csv", dtype=float, delimiter='\t', names=True)

newarray = array*4.0

file.csv 有许多列标题。例如:

array['col_a'] = [5.0, 6.0]

乘以标量后,我想要: newarray['col_a'][20.0, 24.0]

最佳答案

老实说,我很惊讶这在我自己的代码中从未出现过,但事实证明,Numpy 结构化数组(即具有字段名称的数组)don't support the standard arithmetic operators + , - , * ,或/ (见脚注*)。

因此,您唯一的选择是使用数组的非结构化版本。 @hpaulj 的评论指出了您可以这样做的方法(this old answer 包含对如何使用结构化数组进行加法的彻底探索。)。要么索引单个字段(其结果的行为类似于标准数组),然后将其相乘:

import numpy as np
from io import StringIO

csv = '''col_a\tcol_b\tcol_c
5.0\t19.6\t22.8
6.0\t42.42\t39.208
'''

arr = np.genfromtxt(StringIO(csv), dtype=np.float64, delimiter='\t', names=True)

xcol_a = arr['col_a']*4
print(xcol_a)
# output: [20. 24.]

或省略names=True生成数组时使用 kwarg(这使得 np.genfromtxt 返回标准数组而不是结构化数组):

arrstd = np.genfromtxt(StringIO(csv), dtype=np.float64, delimiter='\t', skip_header=True)

print(arrstd*4)
# output: [[ 20.     78.4    91.2  ]
#          [ 24.    169.68  156.832]]

*:从技术上讲,Numpy 的许多内置 ufunc 's 似乎使用结构化数组时不支持。至少一些比较函数/运算符( <>== ) are supported .

关于python - 将数组与标量 : TypeError: invalid type promotion 相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54156904/

相关文章:

python - 同步 PySCXML

Python3,似乎无法理解如何从单个文件中获取信息并将其分发给其他几个文件

python - Python中一定距离内去重

python - numpy.genfromtxt 错误地解析带有转义字符的列名

c++ - 需要跳过每行的最后一个词吗?

python - 在 pandas 中使用 mm-dd-YY 到 YY-mm-dd 格式处理日期

python - 为什么这个 Python 脚本会删除 '.txt' 文件,以及所有 '.tmp' 文件?

python - 确定信号超过预定义限制的时间

具有常量的 Python 矢量化

python - numpy.genfromtxt 跳过/忽略长 tsv 文件中的最后一行