我是使用 python 的新手,出于作業目的,我在這里尋求您的幫助。
我在同一個檔案夾中每個月都有 12 個 excel 檔案,其中包含以下列:Product_Name、Quantity 和 Total_Value
所以,我想做但我不知道該怎么做的是:
- 在每個包含檔案名中相同日期的檔案上添加一個月份列
- 將這些 excel 檔案合并成一個唯一的檔案
例如:
1 月 21 日.xls:
| 產品名稱(型別:字串) | 數量(型別:浮動) | Total_Value(型別:浮點數) | 月份(型別:日期) |
|---|---|---|---|
| 產品A | 10 | 250 | “檔案名”(1 月 21 日) |
| 產品B | 20 | 500 | “檔案名”(1 月 21 日) |
| 產品C | 15 | 400 | “檔案名”(1 月 21 日) |
二月-21.xls:
| 產品名稱(型別:字串) | 數量(型別:浮動) | Total_Value(型別:浮點數) | 月份(型別:日期) |
|---|---|---|---|
| 產品A | 40 | 800 | “檔案名”(2 月 21 日) |
| 產品B | 25 | 700 | “檔案名”(2 月 21 日) |
| 產品C | 30 | 500 | “檔案名”(2 月 21 日) |
合并后:
| 產品名稱(型別:字串) | 數量(型別:浮動) | Total_Value(型別:浮點數) | 月份(型別:日期) |
|---|---|---|---|
| 產品A | 10 | 250 | “檔案名”(1 月 21 日) |
| 產品B | 20 | 500 | “檔案名”(1 月 21 日) |
| 產品C | 15 | 400 | “檔案名”(1 月 21 日) |
| 產品A | 40 | 800 | “檔案名”(2 月 21 日) |
| 產品B | 25 | 700 | “檔案名”(2 月 21 日) |
| 產品C | 30 | 500 | “檔案名”(2 月 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)
所以,我的主要問題是創建一個回圈,在將所有這些檔案合并為一個之前添加月份列。
uj5u.com熱心網友回復:
這與我每天在作業中所做的非常相似。以下是我將如何解決您的問題:
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)
uj5u.com熱心網友回復:
在基本層面上,您首先需要讀取 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 為 Month 列。向每個資料框添加日期列:
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])
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/395562.html
下一篇:查找另一個區間內的所有非重疊區間
