You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在NumPy中获取数组唯一值的数量而非值本身?

获取NumPy数组中唯一元素的数量

嗨,这问题很常见,我来帮你快速解决~

你现在用np.unique(station)得到的是去重后的元素数组,要拿到唯一元素的数量,只需要取这个数组的长度就可以了!这里有两种简洁的实现方式:

方法1:直接取唯一数组的长度

这是最直观的方式:

import numpy as np

station = [28450., 29980.]
# 先获取去重后的数组
unique_stations = np.unique(station)
# 取数组长度就是唯一元素的数量
station_count = len(unique_stations)

print("The number of unique stations is ", station_count)

运行后就会输出:The number of unique stations is 2

方法2:利用return_counts参数(可选)

如果你同时需要每个唯一元素的出现次数,可以用np.unique的return_counts=True参数,它会返回两个值:去重数组和对应的计数数组,之后取计数数组的长度也能得到结果:

import numpy as np

station = [28450., 29980.]
unique_stations, count_array = np.unique(station, return_counts=True)
# 计数数组的长度等于唯一元素的数量
station_count = len(count_array)

print("The number of unique stations is ", station_count)

为什么之前的count方法不行?

你提到尝试过count方法但语法错误,应该是混淆了列表的count()方法——这个方法是用来统计单个元素在列表中出现的次数(比如station.count(28450.)会返回1),而不是统计去重后元素的总数,所以不符合你的需求哦。

内容的提问来源于stack exchange,提问作者mkw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:34:40