【问题标题】:Python + Regex + CSV + Pandas : failed to produce numeric values from alpha-numeric valuesPython + Regex + CSV + Pandas:无法从字母数字值生成数值
【发布时间】:2019-08-16 11:18:14
【问题描述】:

我正在从多页 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 文件中的样本数据:

【问题讨论】:

  • 我不太了解正则表达式来回答您的问题,但也许 read_excel 中的“转换器”参数接受 dict 作为转换映射,可以帮助您吗?如果您可以将您的正则表达式规则插入到字典中,它可能比事后分配值更好。另外,您是否尝试以数字类型阅读?
  • 如果您可以提供源文件中的一些示例数据,即前 2-3 行,将会很有帮助
  • @kerwei:请检查我的编辑。
  • 如果数字单位总是从索引 0 开始,使用正则表达式似乎有点过头了。一个简单的str.split(' ')[0] 也应该让你知道正确的号码吗?

标签: python regex pandas csv


【解决方案1】:

由于您想将1 pkt 之类的任何文本更改为1,而不是使用[a-z]+ 进行拆分,因此最好替换并更改此行:

item[3] = re.split('[a-z]+', item[3])[0]

到:

item[3] = re.sub(r'\D*', '', str(item[3]))

这会将任何非数字字符替换为空字符串。

让我知道这是否有效。如果没有,你能打印item[3] 的值并显示它打印的内容吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多