繁体   English   中英

Pandas - 循环目录 read_excel 使用工作簿月份将日期值添加到数据框

[英]Pandas - loop directory read_excel add date values to dataframe using workbook month

我有一个包含 excel 文件的目录,我正在循环遍历这些文件并将每个文件的工作表读取到 Pandas 数据帧中。 每个文件都包含一个月的数据(示例名称 =“Savings January 2019.xlsx”)。 Excel 表中没有日期列,因此我想在数据框中添加一列“日期”,并按工作簿名称中的月份和年份读取每个文件(例如“2019 年 1 月”)和添加“MM-DD-YYYY”(例如“01-01-2019”作为读入的每一行的日期值。

下面是我在没有日期的情况下读取 12 个 excel 工作簿的工作循环,仅生成所有 12 个月的总数。 我需要日期,以便我可以按月可视化数据。

df_total = pd.DataFrame()

for file in files:        # loop through Excel files (each file adds date value based on file name)

    if file.endswith('.xlsx'):
        excel_file = pd.ExcelFile(file)
        sheets = excel_file.sheet_names

        for sheet in sheets:               # loop through sheets inside an Excel file
            df = excel_file.parse(sheet_name = "Group Savings")
            df_total = df_total.append(df)

当前 df:

     State        Group      Value
0   Illinois    000000130   470.93
1   Illinois    000000130   948.33
2   Illinois    000000784   3498.42
3   Illinois    000000784   16808.16
4   Illinois    000002077   7.00

需要 df:

     State        Group        Date           Value
0   Illinois    000000130   01-01-2019        470.93
1   Illinois    000000130   01-01-2019        948.33
2   Illinois    000000784   01-01-2019       3498.42
3   Illinois    000000784   02-01-2019       6808.16
4   Illinois    000002077   02-01-2019          7.00

我做了一些研究,并认为这类似于创建列然后添加日期值,但无法弄清楚如何解析文件名来这样做,而且我显然是这里的初学者。

for sheet in sheets:               # loop through sheets inside an Excel file
   df = excel_file.parse(sheet_name = "Group Savings")
   df_total = df_total.append(df)
   df_total['Date'] = #if excel_file contains 'January 2019', then df_total['Date'] == '01-01-2019

你的概念是对的,你的代码几乎就在那里。 您现在需要添加的只是日期解析。

您可以使用 Python 的 strptime() 来解析文件名中的日期。

https://docs.python.org/3/library/datetime.html

例如,如果您有一个类似“Savings January 2019.xlsx”的文件名,那么您可以像下面那样解析它。 请注意,这不是解析字符串的唯一方法,还有其他几种变体可以使用此方法。

from datetime import datetime
string = 'Savings January 2019.xlsx'
month_str = string.split(' ')[1]
year_str = string.split(' ')[2].split('.')[0]
date_object = datetime.strptime(month_str + year_str, "%B%Y")

这是 Python 日期字符串格式的一个很好的概述: https : //strftime.org/

拥有日期对象后,您只需立即将其添加到数据框中即可。

df['Date'] = date_object

感谢罗伯特的帮助! 这是最终的代码。 请注意文件名实际上更长,并且我遗漏了一些公司信息,因此 .split 中的更改

from datetime import datetime

#create empty dataframe
df_total = pd.DataFrame()

# loop through Excel files
for file in files:                         
    if file.endswith('.xlsx'):
        excel_file = pd.ExcelFile(file)

        # parse excel filename to take month and year and save as date object for Date column
        month_str = file.split(' ')[4]      
        year_str = file.split(' ')[5].split('.')[0]
        date_object = datetime.strptime(month_str + year_str, "%B%Y")   
        
        # loop excel sheets and add "Date" column, populating with date from parsed filename
        sheets = excel_file.sheet_names
        for sheet in sheets:          # loop through sheets inside an Excel file         
            df = excel_file.parse(sheet_name = "Group Savings")
            df_total = df_total.append(df)
            df_total['Date'] = date_object

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM