![](/img/trans.png)
[英]Python regex alpha-numeric string with numeric part between two values
[英]Python + Regex + CSV + Pandas : failed to produce numeric values from alpha-numeric values
我正在从多页xlsx文件中获取数据,并将数据存储在单独的csv文件中。 xslx中所有工作表的第一行存储在第一csv中,所有工作表的第二行存储在第二csv中,依此类推。 现在,有时第3列到第10列的任何单元格都包含字母数字值,例如“ 1 pkt”。 我只需要使这些值成为数字即可,例如“ 1”,这样我就可以将这些值提供给ML模型以进行预测。 为此,我编写了一个代码:
xls = xlrd.open_workbook(r'Smallys ORDER.xlsx', on_demand=True)
df_list = []
names = xls.sheet_names()
names.remove('EVENT')
for i in range(191):
rows = []
for name in names:
count = 0
prod = pd.read_excel('Smallys ORDER.xlsx', name, index_col=None, header=0)
prod['date'] = name
prod.fillna(0, inplace=True)
try:
item = prod.iloc[i]
item[3] = re.split('[a-z]+', item[3])[0]
print(item[3])
'''item[4] = item[4].split(sep, 1)[0]
item[5] = item[5].split(sep, 1)[0]
item[6] = item[6].split(sep, 1)[0]
item[7] = item[7].split(sep, 1)[0]
item[8] = item[8].split(sep, 1)[0]
item[9] = item[9].split(sep, 1)[0]
item[10] = item[10].split(sep, 1)[0]'''
rows.append(item)
except:
print('Row finished !!!')
writer = csv.writer(open('/home/hp/products/' + 'prod['+str(i)+'].csv', 'w'))
writer.writerow(prod.columns.tolist())
writer.writerows(rows)
print(item[3])
语句不打印任何内容。 另外,在生成的CSV中,仅打印标题。 所有单元格都是空的。
编辑:
在应用任何正则表达式之前,这:
item = prod.iloc[i]
print(item[3])
print(type(item[3]))
打印此:
0
<class 'int'>
0
<class 'int'>
0
<class 'int'>
0
<class 'int'>
0
<class 'int'>
0
<class 'int'>
0
<class 'int'>
1 btl
<class 'str'>
0
<class 'int'>
因此,值可以是整数或字符串。
来自原始xlsx文件表的样本数据:
由于您要将1 pkt
类的任何文本更改为1
,而不是使用[az]+
分割,因此最好替换并更改此行:
item[3] = re.split('[a-z]+', item[3])[0]
至:
item[3] = re.sub(r'\D*', '', str(item[3]))
它将所有非数字字符替换为空字符串。
让我知道这个是否奏效。 如果不是,您可以打印item[3]
的值并显示其打印内容吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.