【问题标题】:Add a month column to each excel file and then merge all files into a .csv为每个 excel 文件添加月份列,然后将所有文件合并为 .csv
【发布时间】:2022-01-26 18:36:56
【问题描述】:

我是使用 python 的新手,出于工作目的,我在这里寻求您的帮助。

我在同一个文件夹中每个月都有 12 个 excel 文件,其中包含以下列:Product_Name、Quantity 和 Total_Value

所以,我想做但我不知道该怎么做是:

  1. 在每个文件名中包含相同日期的文件上添加一个月份列
  2. 将这些 excel 文件合并到一个唯一的文件中

例如:

1 月 21 日.xls:

Product_Name (type:string) Quantity (type:float) Total_Value (type:float) Month (type:Date)
Product A 10 250 "File Name" (January-21)
Product B 20 500 "File Name" (January-21)
Product C 15 400 "File Name" (January-21)

2 月 21 日.xls:

Product_Name (type:string) Quantity (type:float) Total_Value (type:float) Month (type:Date)
Product A 40 800 "File Name" (February-21)
Product B 25 700 "File Name" (February-21)
Product C 30 500 "File Name" (February-21)

合并后:

Product_Name (type:string) Quantity (type:float) Total_Value (type:float) Month (type:Date)
Product A 10 250 "File Name" (January-21)
Product B 20 500 "File Name" (January-21)
Product C 15 400 "File Name" (January-21)
Product A 40 800 "File Name" (February-21)
Product B 25 700 "File Name" (February-21)
Product C 30 500 "File Name" (February-21)

有可能吗?对不起,我的英语不好,我不是母语人士。

非常感谢您的帮助!


编辑.1

这就是我合并、创建 csv 文件并使用 pandas 转换为数据框的方式:


import pandas as pd
import os

path = "/content/drive/MyDrive/Colab_Notebooks/sq_datas"
files = [file for file in os.listdir(path) if not file.startswith('.')] # Ignore hidden files

all_months_data = pd.DataFrame()

for file in files:
    current_data = pd.read_excel(path+"/"+file)
    all_months_data = pd.concat([all_months_data, current_data])
    
all_months_data.to_csv("/content/drive/MyDrive/Colab_Notebooks/sq_datas/all_months.csv", index=False)

所以,我的主要问题是创建一个循环,以便在将所有这些文件合并为一个之前添加月份列。

【问题讨论】:

  • 欢迎来到Stack Overflow. 请注意这不是代码编写或辅导服务。我们可以帮助解决具体的技术问题,而不是对代码或建议的开放式请求。请编辑您的问题以显示您迄今为止尝试过的内容,以及您需要帮助的具体问题。请参阅How To Ask a Good Question 页面,详细了解如何最好地帮助我们。
  • 哦,对不起,我将编辑这篇文章并展示我试图做什么以及如何合并这些文件。

标签: python pandas csv date glob


【解决方案1】:

在基本层面上,您首先需要阅读您的 Excel 文件,例如 pandas.read_excel

import pandas as pd

jan21_df = pd.read_excel('January-21.xls')
feb21_df = pd.read_excel('February-21.xls')

您为月份列写了 type:Date。向每个数据框添加日期列:

jan21_df['Month'] = pd.to_datetime('2021-01-01')
feb21_df['Month'] = pd.to_datetime('2021-02-01')

但是如果你想要文件名作为字符串:

jan21_df['Month'] = "File Name (January-21)"
feb21_df['Month'] = "File Name (February-21)"

然后合并两个数据框:

combined = pd.concat([jan21_df, feb21_df])

这是一个概念证明。有一些方法可以根据需求进一步自动化。

编辑:基于 OP 中的编辑,对循环进行少量添加:

for file in files:
    current_data = pd.read_excel(path+"/"+file)
    current_data['Month'] = file
    all_months_data = pd.concat([all_months_data, current_data])

【讨论】:

  • 哦,它就像一个魅力,只需添加以下行: current_data['Month'] = file 我也做了一些更改,拆分 .xls,然后将 January-21 转换为日期时间格式。做得好,非常感谢!
  • 非常好,您添加的最终格式更改做得很好。
【解决方案2】:

这与我每天在工作中所做的非常相似。以下是我将如何解决您的问题:

from pathlib import Path

path = Path("/content/drive/MyDrive/Colab_Notebooks/sq_datas")
all_data = []

for file in path.glob("*.xls"):
    # Parse the month from the file's name
    # month will be something like "January" and "February"
    # year will be something like "20" and "21"
    # date will be something like pd.Timestamp("2021-01-01")
    month, year = file.stem.split("-")
    date = pd.Timestamp(f"{month} 1, 20{year}")
    
    # Read data from the current file
    current_data = pd.read_excel(file).assign(Month=date)

    # Append the data to the list
    all_data.append(current_data)

# Combine all data from the list into a single DataFrame
all_data = pd.concat(all_data)

【讨论】:

  • 我收到错误:ValueError: could not convert string to Timestamp 我应该使用格式字符串来日期格式,例如:%m-%d-%y 吗?
  • 设置断点并检查monthyear是否符合预期
猜你喜欢
  • 2020-08-31
  • 2019-03-25
  • 1970-01-01
  • 1970-01-01
  • 2018-03-30
  • 1970-01-01
  • 2019-03-14
  • 2017-04-13
  • 2019-10-11
相关资源
最近更新 更多