我试图将 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/