【问题标题】:How to perform bincount on an array of strings?如何对字符串数组执行 bincount?
【发布时间】:2018-03-12 05:09:56
【问题描述】:

我有包含字符串值的 NumPy 数组。

例如:["bus", "bar", "bar", "cafe" .....]

计算数组中每个元素出现次数的最佳方法是什么。我目前的解决方案是:

# 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,但它不适用于此类数据。

你知道更好的解决方案吗?

【问题讨论】:

  • 使用pd.factorize然后使用np.bincount

标签: python arrays string pandas numpy


【解决方案1】:

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

有点迂回,但很有趣。

【讨论】:

  • 最佳答案是 .value_counts() 仅供参考
  • @Jeff 更新了,谢谢,我不知道这是一个模块级函数。
  • 您也可以将return_countsnp.unique 一起使用,从而完全避免使用bincount
  • @Divakar 哇!我什至不知道这是可能的。感谢您的宝贵建议 - 我已编辑。
【解决方案2】:

你也可以在python中使用字典。

result_dict = {}
l = ['bus', 'bar', 'bar', 'café', 'bus', 'bar', 'café']
for ele in l:
    result_dict[ele] = 1 if ele not in result_dict else result_dict[ele] + 1

然后打印结果:

for key in result_dict:
    print key, result_dict[key]

结果:

bus 2
bar 3
café 2

【讨论】:

    猜你喜欢
    • 2011-05-12
    • 2021-08-13
    • 1970-01-01
    • 2016-11-10
    • 2023-03-27
    • 1970-01-01
    • 2013-06-14
    • 1970-01-01
    • 2021-03-16
    相关资源
    最近更新 更多