python - 使用numpy根据固定映射将巨大的2字节字符串数组转换为相应的1字节字符串

标签 python arrays numpy translation

我有一组 12 个不同的 2 字节字符串,根据以下翻译字典映射到一组 12 个相应的 1 字节字符串:

translation_dict = {'AC': '2', 'AG': '3', 'AT': '4',
                    'CA': '5', 'CG': '6', 'CT': '7', 
                    'GA': '8', 'GC': '9', 'GT': 'a', 
                    'TA': 'b', 'TC': 'c', 'TG': 'd'}

我需要一些方法将巨大的 2 字节字符串转换为相应的 1 字节字符串映射,如以下示例所示:

>>> input_array = numpy.char.array(['CA', 'CA', 'GC', 'TC', 'AT', 'GT', 'AG', 'CT'])
>>> output_array = some_method(input_arr)
>>> output_array
chararray(['5', '5', '9', 'c', '4', 'a', '3', '7'], dtype='S1')

我想知道是否有一个快速的 numpy.char.array 方法来翻译 2 字节字符串的巨大数组;我知道我可以将“numpy.vectorize”与一个函数一起使用,该函数显式查找每个 2 字节键的 1 字节字典值,但这相对较慢。我无法弄清楚如何使用 numpy.chararray.translate,尽管它似乎在任何情况下都只适用于 1 字节:1 字节映射。

最佳答案

对于此类搜索操作,NumPy 有 np.searchsorted ,所以请允许我提出一种方法 -

def search_dic(dic, search_keys):
    # Extract out keys and values
    k = dic.keys()
    v = dic.values()

    # Use searchsorted to locate the indices
    sidx = np.argsort(k)
    idx = np.searchsorted(k,search_keys, sorter=sidx)

    # Finally index and extract out the corresponding values
    return np.take(v,sidx[idx])

示例运行 -

In [46]: translation_dict = {'AC': '2', 'AG': '3', 'AT': '4',
    ...:                     'CA': '5', 'CG': '6', 'CT': '7', 
    ...:                     'GA': '8', 'GC': '9', 'GT': 'a', 
    ...:                     'TA': 'b', 'TC': 'c', 'TG': 'd'}

In [47]: s = np.char.array(['CA', 'CA', 'GC', 'TC', 'AT', 'GT', 'AG', 'CT'])

In [48]: search_dic(translation_dict, s)
Out[48]: 
array(['5', '5', '9', 'c', '4', 'a', '3', '7'], 
      dtype='|S1')

关于python - 使用numpy根据固定映射将巨大的2字节字符串数组转换为相应的1字节字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43255679/

相关文章:

python - AttributeError 'tuple' 对象没有属性 'values' django rest framework

c# - 如何用C#中的特定间隔分隔的数字初始化数组

python - 将 csv 列加载到 numpy 内存映射中(快速)

Python 安装 mpi4py.MPI

python - 并发 psycopg2 postgres 选择查询的空结果

python - pytesseract Windows错误: [Error 5] Access is denied

c# - 尝试在 C# 中对数组进行排序时出现编译错误

c++ - 数组溢出 C++(在 arr[0])?

python - 重复索引列表

python - 在 Python 中重现涉及 for 循环的 MATLAB 代码时出现问题