如何在numpy.ndarray中拆分字符串生成一维数组?
解决方法
下面两种方法均可实现将numpy数组中带|的元素拆分并转换为一维数组:
方法一:列表推导式(简洁高效)
遍历原数组的每个元素,拆分后直接收集所有句子,最后转为numpy数组:
import numpy as np # 原数组 arr = np.array([ 'This is example sentence 1.|This is example sentence 2.', 'This is example sentence 3.', 'This is example sentence 4.', 'This is example sentence 5.', 'This is example sentence 6.|This is example sentence 7.|This is example sentence 8.|This is example sentence 9.|This is example sentence 10.' ]) # 拆分并生成结果数组 result = np.array([sent for item in arr for sent in item.split('|')]) print(result)
方法二:numpy向量化函数
利用np.vectorize对数组元素批量拆分,再拼接成一维数组:
import numpy as np arr = np.array([ 'This is example sentence 1.|This is example sentence 2.', 'This is example sentence 3.', 'This is example sentence 4.', 'This is example sentence 5.', 'This is example sentence 6.|This is example sentence 7.|This is example sentence 8.|This is example sentence 9.|This is example sentence 10.' ]) # 定义向量化拆分函数 split_vectorized = np.vectorize(lambda x: x.split('|')) # 拆分每个元素得到嵌套数组 split_result = split_vectorized(arr) # 拼接成一维数组 final_arr = np.concatenate(split_result) print(final_arr)
为什么直接用split失败?
numpy数组本身没有split方法,必须对数组中的每个元素单独执行字符串拆分操作,上述两种方法都是针对单个元素处理后再整合的思路。
内容的提问来源于stack exchange,提问作者Rycliff
相关产品推荐
相关产品推荐

