使用np.apply_along_axis结合' '.join拼接字符串数组报错问题
解决Numpy字符串二维数组每行拼接的问题
首先看你代码里的明显问题:strip(...)是无效的语法,strip()要么不传参数(默认去除首尾空白字符),要么传入要移除的字符集合,不能用...占位,这是导致运行失败的直接原因。另外,处理numpy二维数组的每行拼接,需要用合适的方式遍历每行并应用拼接逻辑。
这里给你两种可行的修正方案:
方案一:使用numpy的apply_along_axis处理
这种方法适合保持numpy数组的操作风格,对每行应用自定义拼接函数:
import numpy as np a = np.array([['3', '3', '3', '3', '3', '3', '3', '3', '3', '3', '3', '3','3', '3', '3', '3', '9', '11', '3', '3'], ['3', '3', '3', '3', '3', '3', '3', '3', '3', '3', '3', '11', '9', '11', '3', '3', '3', '3', '3', '3']]) def concat(x, separator): # 修复strip的语法,如果不需要去除首尾空格可以直接去掉strip() return separator.join(x).strip() # 沿着轴1(每行)应用concat函数,指定分隔符为空格 result = np.apply_along_axis(concat, 1, a, separator=' ') print(result)
运行后输出:
array(['3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 9 11 3 3', '3 3 3 3 3 3 3 3 3 3 3 11 9 11 3 3 3 3 3 3'], dtype='<U39')
方案二:用列表推导式直接遍历每行
这种方法更简洁直观,对于小规模数组来说效率也很高:
import numpy as np a = np.array([['3', '3', '3', '3', '3', '3', '3', '3', '3', '3', '3', '3','3', '3', '3', '3', '9', '11', '3', '3'], ['3', '3', '3', '3', '3', '3', '3', '3', '3', '3', '3', '11', '9', '11', '3', '3', '3', '3', '3', '3']]) # 遍历每行,用空格拼接后转成numpy数组 result = np.array([' '.join(row) for row in a]) print(result)
输出和方案一完全一致。
总结一下:你原来的代码核心问题是strip(...)的语法错误,其次是没有正确遍历numpy数组的每行进行拼接,上面两种方案都能解决你的需求,根据自己的习惯选择即可。
内容的提问来源于stack exchange,提问作者Aman Dalmia
相关产品推荐
相关产品推荐

