我有一个包含字符串值的 NumPy 数组。
例如:["bus", "bar", "bar", "café".....]
计算数组中每个元素出现次数的最佳方法是什么。我目前的解决方案是:
# my_list contains my data.
bincount = []
for name in set(my_list.tolist()):
count = sum([1 for elt in my_list if elt == name])
bincount.append(count)
我试过 bincount 但它不适用于这种类型的数据。
你知道更好的解决方案吗?
最佳答案
np.unique
l = ['bus', 'bar', 'bar', 'café', 'bus', 'bar', 'café']
a, b = np.unique(l, return_counts=True)
a
# array(['bar', 'bus', 'café'], dtype='<U4')
b
# array([3, 2, 2])
pd.value_counts
pd.value_counts(l)
bar 3
bus 2
café 2
dtype: int64
# <=0.23
pd.value_counts(l).values
# 0.24+
pd.value_counts(l).to_numpy()
# array([3, 2, 2])
确保已导入 pandas(import pandas as pd
)。
pd.factorize
np.bincount(pd.factorize(l)[0])
# array([2, 3, 2])
这会将字符串转换为数字类别(或因子,如果您愿意),并对它们进行计数。
pd.get_dummies
pd.get_dummies(l).sum()
bar 3
bus 2
café 2
dtype: int64
有点迂回,但仍然很有趣。
关于python - 如何对字符串数组执行 bincount?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46503331/