Multiplying ndarray with scalar: TypeError: invalid type promotion

Multiplying ndarray with scalar: TypeError: invalid type promotion

我正在尝试将 ndarray 中的每一列乘以一个标量。当我尝试这样做时,出现错误 TypeError: invalid type promotion.

我试过使用 array.astype(float),但这给出了所有 NaNs。

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

newarray = array*4.0

file.csv 有多个列 headers。例如:

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

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

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

因此,您唯一的选择是使用阵列的非结构化版本。 @hpaulj 的评论指出了您可以这样做的方法( 包含对如何获得附加功能以使用结构化数组的彻底探索。)。索引单个字段(其结果类似于标准数组)并将其相乘:

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 return 成为标准数组而不是结构化数组):

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 not supported when working with structured arrays. At least some of the comparison functions/operators (<, >, and ==) are supported.