问题描述
我有一个1m +行的数据集,每行都有小写/大写字母,符号和数字的组合。我希望清除此数据,并且仅保留小写字母和数字彼此相邻的最后一个实例。为了提高速度,我目前的计划是将这些数据存储为字符串数组,然后使用.findall操作保持我要查找的字母/数字组合。
以下是我尝试做的事情:
输入
list = Array(["Nd4","0-0","Nxe4","e8+","e4g2"])
newList = list.findall('[a-z]\d')[len(list.findall('[a-z]\d')-1]
newList的预期输出
newList = ("d4","","e4","e8","g2")
解决方法
不建议使用“列表”来分配变量,因为它是内置函数
import re
import numpy as np
lists = np.array(["Nd4","0-0","Nxe4","e8+","e4g2"])
def findall(i,pattern=r'[a-z1-9]+'):
return re.findall(pattern,i)[0] if re.findall(pattern,i) else ""
newList = [findall(i) for i in lists]
# OR if you want to return an array
newList = np.array(list(map(findall,lists)))
# >>> ['d4','','xe4','e8','e4g2']
,
这可能不是最漂亮的方法,但是我认为它可以完成工作!
import re
import numpy as np
lists = np.array(["Nd4","e4g2"])
def function(i):
try:
return re.findall(r'[a-z]\d',i)[len(re.findall(r'[a-z]\d',i))-1]
except:
return ""
newList = [function(i) for i in lists]