困在这个Numpy问题上
country=['India','USA']
gdp=[22,33]
import numpy as np
a=np.column_stack((country,gdp))
array([['India', '22'],
['USA', '33']], dtype='<U11')
我有一个NDArray,我想找到第二列的最大值。我尝试了下面的方法
print(a.max(axis=1)[1])
print(a[:,1].max())
它抛出了以下错误:TypeError: cannot perform reduce with flexible type
尝试转换类型
datatype=([('country',np.str_,64),('gross',np.float32)])
new=np.array(a,dtype=datatype)
但是得到了下面的错误
无法将字符串转换为浮动:“印度”。
发布于 2018-03-19 10:00:24
错误是由于数组中的字符串数据造成的,这使得dtype成为unicode(由U11表示,即11字符unicode)字符串。如果您希望以数字格式存储数据,请使用structured arrays
。但是,如果只希望计算数值列的最大值,请使用
print(a[:, 1].astype(np.int).max())
// 33
您可以根据特定列中数据的性质选择使用其他数字类型,例如np.float
替换np.int
。
发布于 2018-03-19 10:12:17
考虑对混合类型使用numpy
结构化数组。如果显式设置数据类型,则不会出现任何问题。
这在numpy
中通常是必要的,当然也是可取的。
import numpy as np
country = ['India','USA','UK']
gdp = [22,33,4]
a = np.array(list(zip(country, gdp)),
dtype=[('Country', '|S11'), ('Number', '<i8')])
res_asc = np.sort(a, order='Number')
# array([(b'UK', 4), (b'India', 22), (b'USA', 33)],
# dtype=[('Country', 'S11'), ('Number', '<i8')])
res_desc = np.sort(a, order='Number')[::-1]
# array([(b'USA', 33), (b'India', 22), (b'UK', 4)],
# dtype=[('Country', 'S11'), ('Number', '<i8')])
https://stackoverflow.com/questions/49359952
复制相似问题