【问题标题】:Python: Extract field values into new columns, write to ExcelPython:将字段值提取到新列中,写入 Excel
【发布时间】:2020-05-29 14:07:45
【问题描述】:

我正在读取 CSV 文件并打算写入 Excel 文件。 CSV 文件只有两列,但我想在写入 Excel 之前使用正则表达式提取列数据并创建新列。

CSV 文件:test.csv

name, file_info
test, c:\folder1\subfolder1\subfolder2\example.xls | history 12345 at 2020-01-01

这是我目前的代码:

import csv

with open('test.csv',mode='r') as testFile
     reader = csv.DictReader(testFile, delimiter=',')
     for row in reader:
          ### This is where i assume i need to perform the regex operation on the current row

我想将文件名 (example.xlsx)、历史记录 (12345) 和日期 (2020-01-01) 提取为 Excel 文件中的列。

我成功地测试了一个正则表达式

"\\([^\\|]*)\s*\|\"

我确信有多种方法可以做到这一点。熊猫会更好吗?我可以通过以下方式简单地读取和写入文件到 excel:

df = pd.read_csv('test.csv')
df.to_excel('text.xlsx)

我对 Pandas 没有任何经验,因此不确定如何使用正则表达式执行我想要的操作并将它们结合在一起。

最终产品是一个包含五 (5) 列的 Excel 电子表格

name | path | file | history | date

【问题讨论】:

  • 使用 Pandas,看看使用 df[['newcol1', 'newcol2']] = DataFrame.loc['colname'].str.extract(REGEX) 逻辑。显然,您的字段和正则表达式模式。这会将 named regex groups 提取到 DataFrame 的新列中。有点厉害。
  • 请给我们一些CSV的示例行吗?
  • 我对 Pandas 没有任何经验,所以不知道如何使用正则表达式执行我想要的操作并将它们结合在一起。 Stack Overflow 不是代替您需要的指南、教程或文档。请参阅:tourHow to Askhelp center
  • 这里有更多的 CSV
  • 名称,file_info test1,c:\folder1\subfolder1\subfolder2\example1.xls |历史 12345 在 2020-01-01 test2,c:\folder1\subfolder1\subfolder2\example2.xls |历史 24687 在 2020-01-12 test3,c:\folder1\subfolder1\subfolder2\example3.xls |历史 33445 在 2020-01-13 test4,c:\folder1\subfolder1\subfolder2\example4.xls |历史 55664 在 2020-01-14

标签: python regex pandas csv


【解决方案1】:

这是一种使用 Pandas df['column'].str.extract() 函数的技术。

您可以将已编译(或未编译)的正则表达式字符串传递给extract() 函数。这将使用表达式中的命名组并将这些组提取到具有相同名称的列中。

样本数据:

name,file_info
test1,c:\folder1\subfolder1\subfolder2\example1.xls | history 12345 at 2020-01-01
test2,c:\folder1\subfolder1\subfolder2\example2.xls | history 24687 at 2020-01-12
test3,c:\folder1\subfolder1\subfolder2\example3.xls | history 33445 at 2020-01-13
test4,c:\folder1\subfolder1\subfolder2\example4.xls | history 55664 at 2020-01-14

代码:

import os
import pandas as pd
import re

# Define constants
COLS = ['name', 'path', 'file', 'history', 'date']
PATH = './test.csv'
PATH_XL = './test.xlsx'
RE_EXP = re.compile(r'^'
                    '(?P<path>.*)\|\shistory\s'
                    '(?P<history>\d+)\sat\s'
                    '(?P<date>\d{4}-\d{2}-\d{2})$',
                    re.IGNORECASE)

# Read CSV file.
df = pd.read_csv(PATH)
# Create new columns using named regex groups.
df[['path', 'history', 'date']] = df['file_info'].str.extract(RE_EXP)
# Extract the filename from the path using a built-in function.
df['file'] = df['path'].apply(os.path.basename)
# Convert date to datetime format.
df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d').dt.date
# Subset DataFrame to only the columns we require.
df = df[COLS]
# Write results to Excel.
df.to_excel(PATH_XL, index=False)

Excel 输出:

【讨论】:

  • 谢谢。我创建了一个测试文件来测试您的代码并获得多个异常。第一个是 KeyError: 'file_info' on line 18: "df[['path', 'history', 'date']] = df['file_info'].str.extract(RE_EXP)"
  • 好的。确保 1) 您的列名是 namefile_info,以及 2) 没有前导/训练空格。所以你的标题必须是:name,file_info.
  • 好的,我想我已经成功了。一样东西。如何删除日期格式的时间?我只想要'2020-01-01'
  • 只需将.dt.date 添加到日期时间转换的末尾即可。这会将Series 转换为datetime 对象,.date 属性仅检索日期。请参阅编辑后的答案。如果这对您有用,请接受答案。谢谢!
  • 您已经有一段时间没有帮助我解决我的问题了。我正在重新访问此代码,并在df['file'] = df['path'].apply(os.path.basename) 行出现错误我得到的错误是 TypeError: expected str, bytes or os.PathLike object, not float。我不确定它是否与现在使用 Python 3.7 有关,但代码现在不适合我。提前致谢
猜你喜欢
  • 2013-10-12
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
  • 2012-04-13
  • 2013-04-04
  • 1970-01-01
  • 2021-12-01
相关资源
最近更新 更多