如何处理 numpy 数组中的混合数据类型 [英] How to handle mixed data types in numpy arrays

查看:98
本文介绍了如何处理 numpy 数组中的混合数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

陷入这个 Numpy 问题

Stuck in this Numpy Problem

country=['India','USA']
​gdp=[22,33]

import numpy as np
a=np.column_stack((country,gdp))

array([['India', '22'],
       ['USA', '33']], dtype='<U11')

我有一个 NDArray,我想找到第二列的最大值.我试过下面的

I have an NDArray and I want to find the maximum of the 2nd column. I tried the below

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)

但出现以下错误

无法将字符串转换为浮点数:'India'.

could not convert string to float: 'India'.

推荐答案

该错误是由于数组中的字符串数据导致 dtype 为 Unicode(由 U11 表示,即 11 个字符的 unicode)字符串.如果您希望以数字格式存储数据,请使用结构化数组.但是,如果您只想计算数值列的最大值,请使用

The error is due to the string data in your array, which makes the dtype to be Unicode(indicated by U11 i.e., 11-character unicode) string. If you wish to store data in the numerical format, then use structured arrays. However, if you only wish to compute the maximum of the numerical column, use

print(a[:, 1].astype(np.int).max())
// 33

您可以根据特定列中数据的性质选择使用其他数字数据类型,例如 np.float 代替 np.int.

You may choose to use other numerical dtypes such as np.float inplace of np.int based on the nature of data in the specific column.

这篇关于如何处理 numpy 数组中的混合数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆