【问题标题】:Add date column to each excel workbook depending on the name of the workbook. Using python and pandas根据工作簿的名称向每个 Excel 工作簿添加日期列。使用 python 和熊猫
【发布时间】:2020-12-12 01:20:49
【问题描述】:

我正在尝试将日期列添加到包含来自 Excel 工作簿的数据的每一行。

不太清楚如何开始使用 python 和 pandas。 (在 python 中还是很新的)

文件夹中的文件设置如下:

| Folder Name |
|------|
|All GL Accounts Jan 2020.xlsx|
|All GL Accounts Feb 2020.xlsx|
|All GL Accounts Mar 2020.xlsx|
ETC.

我想在 excel *Jan 2020.xlsx 上读取名称的结尾,并在包含格式化日期的列表中查找它,例如:2020 年 1 月 31 日。

我需要脚本遍历整个文件夹并对每年的每个月进行更改,并为包含数据的每一行添加一个日期列。

提前谢谢大家的帮助!!

【问题讨论】:

  • 太棒了!谢谢!我以前找不到任何东西。
  • 快乐编码 :)
  • 一件事是它们不是 .csv 文件。这会有所作为吗?
  • pd.read_csv 更改为 pd.read_excel,一切顺利

标签: python excel pandas


【解决方案1】:

因此,请向 @Yuca 大声疾呼,因为他们为我指明了正确的方向。我使用了从 fnmatch 中学到的一些知识,并在我的脚本中实现了它。

不确定这是否是最好的处理方式,但它现在正在运行!

如果有人有任何想要添加的内容,我会随时了解更多信息。

import os
import pandas as pd
from fnmatch import fnmatch

date_dict = {
    'Jan 2020':r'01/01/2020',
    'Feb 2020':r'02/01/2020',
    'Mar 2020':r'03/01/2020',
    'Apr 2020':r'04/01/2020',
    'May 2020':r'05/01/2020',
    'Jun 2020':r'06/01/2020',
    'Jul 2020':r'07/01/2020',
    'Aug 2020':r'08/01/2020',
    'Sep 2020':r'09/01/2020',
    'Oct 2020':r'10/01/2020',
    'Nov 2020':r'11/01/2020',
    'Dec 2020':r'12/01/2020',
    }

date_list = (
    'Jan 2020',
    'Feb 2020',
    'Mar 2020',
    'Apr 2020',
    'May 2020',
    'Jun 2020',
    'Jul 2020',
    'Aug 2020',
    'Sep 2020',
    'Oct 2020',
    'Nov 2020',
    'Dec 2020'
    )


patterns = [(date, f"*{date}.xlsx") for date in date_list]

path = r'file_path'
filelist = os.listdir(path) 
for file in filelist:
    print(file)
    for date, pattern in patterns:
        print(pattern)
        print(date)
        if fnmatch(file, pattern):
            frames = []
            df = pd.read_excel(path+'/'+file)
            date_name = date_dict[date]
            df['Date'] = date_name
            print('Matched: ' + file)
            frames.append(df)
            frame = pd.concat(frames)
            frame.to_excel(path +'\\_New_'+ file, index = False)
            break

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-22
    • 2020-12-09
    • 2019-12-24
    • 1970-01-01
    相关资源
    最近更新 更多