如何处理 numpy 数组中的混合数据类型
How to handle mixed data types in numpy arrays
陷入这个 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)
但是出现以下错误
could not convert string to float: 'India'.
错误是由于您的数组中的字符串数据导致dtype为Unicode(由U11表示,即11个字符的unicode)字符串。
如果您希望以数字格式存储数据,请使用 structured arrays
。
但是,如果您只想计算数字列的最大值,请使用
print(a[:, 1].astype(np.int).max())
// 33
您可以根据特定列中数据的性质选择使用其他数字数据类型,例如 np.float
代替 np.int
。
考虑对混合类型使用 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')])
陷入这个 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)
但是出现以下错误
could not convert string to float: 'India'.
错误是由于您的数组中的字符串数据导致dtype为Unicode(由U11表示,即11个字符的unicode)字符串。
如果您希望以数字格式存储数据,请使用 structured arrays
。
但是,如果您只想计算数字列的最大值,请使用
print(a[:, 1].astype(np.int).max())
// 33
您可以根据特定列中数据的性质选择使用其他数字数据类型,例如 np.float
代替 np.int
。
考虑对混合类型使用 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')])