python - 沿轴连接字符串

标签 python numpy

假设我有一个 numpy 字符串数组,如下所示:

import numpy as np
print('numpy version:', np.__version__)

a = np.arange(25).reshape(5, 5)
stra = a.astype(np.dtype(str))

print(stra)

输出:

numpy version: 1.15.2
[['0' '1' '2' '3' '4']
 ['5' '6' '7' '8' '9']
 ['10' '11' '12' '13' '14']
 ['15' '16' '17' '18' '19']
 ['20' '21' '22' '23' '24']]

我想沿着给定的轴工作,选择一些元素,然后连接这些字符串。首先我尝试了这个:

print(np.apply_along_axis('|'.join, 1, stra.take([2, 3], 1)))

但是较长的结果字符串会被截断以匹配最短的字符串:

['2|3' '7|8' '12|' '17|' '22|']

我当然可以编写自己的循环来获得我想要的输出,但是当单行代码几乎可以工作时,这样做有点令人不满意。

def join_along_axis(array, indices, axis):        
    if array.ndim == 1:
        return np.array('|'.join(array.take(indices)))

    joined = []        
    # Move axis of interest to end and flatten others to make the loop easy.
    work_arr = np.rollaxis(array, axis, -1)
    shape = work_arr.shape
    new_shape = (np.product(work_arr.shape[:-1]), work_arr.shape[-1])
    work_arr = work_arr.reshape(new_shape)

    for arr in work_arr:
        joined.append('|'.join(arr.take(indices)))

    return np.array(joined).reshape(shape[:-1])

print(join_along_axis(stra, [2, 3], 1))

输出:

['2|3' '7|8' '12|13' '17|18' '22|23']

是否有比我的 join_along_axis 函数更巧妙的方法?

为清楚起见进行更新:我需要它足够通用,可以处理具有任意维数且沿任何选定轴的数组。

最佳答案

我首先尝试使用 apply_along_axis 按照您的方式进行操作,但我发现这可能会更棘手,apparently NP 对于处理字符串没有很好的定义。

那么列表理解怎么样?

a =a = np.arange(25).reshape(5, 5)
stra = a.astype(np.dtype(str))
only23 = zip(stra[:,2],stra[:,3])
only23

输出:

[('2', '3'), ('7', '8'), ('12', '13'), ('17', '18'), ('22', '23')]

现在让我们进行理解:

[x[0] +'|'+x[1] for x in only23]

输出:

['2|3', '7|8', '12|13', '17|18', '22|23']

你实际上可以让它成为一句台词,我只是不认为它会那么可读

关于python - 沿轴连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52677947/

相关文章:

python - (python) 语法错误 : invalid syntax in def function

python - 求解线性最小二乘法的最快方法

python - 翻转已排序数据框的排序顺序

python - Numpy 标准差不适合我

python - 显示数组内元素的数据类型并将其转换为 Integer。 Python 和 Numpy

python - 如何过滤QComboBox的数据

python - 如何删除 csv 文件中的一列值但不删除第一项?

python - 找出 sqlalchemy orm 中的根引用

python - 如何将 Perlin 噪声值标准化到范围 [0, 1]?

python - 实现 wxpython 的 html2.WebViewHandler 和 html2.WebViewFSHandler 的问题