我想讀取多個 excel 檔案并將它們存盤到單個 Pandas 資料框中,但我希望資料框中的列之一是檔案名。這是因為檔案名包含日期(這是每月資料),我需要該資訊。我似乎無法獲得檔案名,但我能夠將 excel 檔案放入資料框中。請幫忙。
import os
import pandas as pd
import fsspec
files = os.listdir("C://Users//6J2754897//Downloads//monthlydata")
paths = "C://Users//6J2754897//Downloads//monthlydata"
a = pd.DataFrame([2], index = None)
df = pd.DataFrame()
for file in range(len(files)):
if files[file].endswith('.xlsx'):
df = df.append(pd.read_excel(paths "//" files[file], sheet_name = "information", skiprows=7), ignore_index=True)
df['Month'] = str(files[file])
uj5u.com熱心網友回復:
這里的操作順序不正確。線路:
df['Month'] = str(files[file])
將用最新值覆寫整個列。
相反,我們應該只將值添加到當前的DataFrame 中:
import os
import pandas as pd
paths = "C://Users//6J2754897//Downloads//monthlydata"
files = os.listdir(paths)
df = pd.DataFrame()
for file in range(len(files)):
if files[file].endswith('.xlsx'):
# Read in File
file_df = pd.read_excel(paths "//" files[file],
sheet_name="information",
skiprows=7)
# Add to just this DataFrame
file_df['Month'] = str(files[file])
# Update `df`
df = df.append(file_df, ignore_index=True)
或者,我們可以使用DataFrame.assign鏈接列分配:
import os
import pandas as pd
paths = "C://Users//6J2754897//Downloads//monthlydata"
files = os.listdir(paths)
df = pd.DataFrame()
for file in range(len(files)):
if files[file].endswith('.xlsx'):
# Read in File
df = df.append(
# Read in File
pd.read_excel(paths "//" files[file],
sheet_name="information",
skiprows=7)
.assign(Month=str(files[file])), # Add to just this DataFrame
ignore_index=True
)
對于一般的整體改進,我們可以使用pd.concat對檔案的串列理解。這樣做是為了避免增長 DataFrame(可能非常慢)。Pathlib.glob還可以幫助選擇適當的檔案:
from pathlib import Path
import pandas as pd
paths = "C://Users//6J2754897//Downloads//monthlydata"
df = pd.concat([
pd.read_excel(file,
sheet_name="information",
skiprows=7)
.assign(Month=file.stem) # We may also want file.name here
for file in Path(paths).glob('*.xlsx')
])
月份列的一些選項是:
- file.stem將給出“[t] the final path component, without its suffix”。
- “檔案夾/檔案夾/sample.xlsx”->“示例”
- file.name將給出“最終路徑組件,不包括驅動器和根目錄”。
- '檔案夾/檔案夾/sample.xlsx' -> 'sample.xlsx'
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/336091.html
上一篇:僅附加來自第二個資料幀的唯一行
