Skip to main content
 首页 » 编程设计

Python:绘制具有重复条目的字符串数组与没有 for 循环的 float

2024年10月01日30cmt

您好,我正在尝试在 y 轴上绘制一个 numpy 字符串数组,例如

arr = np.array(['a','a','bas','dgg','a']) #The actual strings are about 11 characters long 

与等长的 float 组。我正在使用的字符串数组非常大,大约有 1 亿个条目。我想到的解决方案之一是将字符串数组转换为唯一的整数 ID,例如,

vocab = np.unique(arr) 
vocab = list(vocab) 
arrId = np.zeros(len(arr)) 
for i in range(len(arr)): 
    arrId[i] = vocab.index(arr[i]) 

然后是 matplotlib.pyplot.plot(arrId)。但我不能负担得起运行 for 循环以将字符串数组转换为唯一整数 ID 数组。在最初的搜索中,我找不到不使用循环就可以将字符串映射到唯一 ID 的方法。也许我遗漏了一些东西,但是在 python 中是否有一种聪明的方法来做到这一点?

编辑 -

谢谢。提供的解决方案使用 vocab,ind = np.unique(arr, return_index = True) 其中 idx 是返回的唯一整数数组。但是根据这个(numpy.unique with order preserved),np.unique 似乎是 O(N*log(N)),但是 pandas.unique 是 O(N) 的阶数。但我不确定如何从 pandas.unique 获取 ind。我想绘制数据可以在 O(N) 中完成。所以我想知道有没有办法做到这一点 O(N)?也许通过某种散列?

请您参考如下方法:

numpy.unique 与 return_inverse 参数一起使用可让您获得倒排索引。

arr = np.array(['a','a','bas','dgg','a']) 
unique, rev = np.unique(arr, return_inverse=True) 
 
#unique: ['a' 'bas' 'dgg'] 
#rev: [0 0 1 2 0] 

unique[rev] 返回原始数组 ['a' 'a' 'bas' 'dgg' 'a']。

这可以很容易地用于绘制数据。

import numpy as np 
import matplotlib.pyplot as plt 
 
arr = np.array(['a','a','bas','dgg','a']) 
x = np.array([1,2,3,4,5]) 
 
unique, rev = np.unique(arr, return_inverse=True) 
print unique 
print rev 
print unique[rev] 
 
fig,ax=plt.subplots() 
ax.scatter(x, rev) 
ax.set_yticks(range(len(unique))) 
ax.set_yticklabels(unique) 
 
plt.show()