我有一個將多個 excel 檔案合并到 1 個檔案中的代碼,但我需要添加一列,其中包含所用檔案的名稱(檔案名)。
這是代碼:
import os
import pandas as pd
cwd = os.path.abspath('')
files = os.listdir(cwd)
## Code gets the first sheet of a given file
df = pd.DataFrame()
for file in files:
if file.endswith('.xlsx'):
df = df.append(pd.read_excel(file), ignore_index=True)
df.head()
df.to_excel('Combined.xlsx')
如何為使用的每個檔案添加帶有檔案名的列?
謝謝
uj5u.com熱心網友回復:
只需添加d["filename"] = file當您在 for 回圈中加載 Excel 檔案時:
import os
import pandas as pd
cwd = os.path.abspath('')
files = os.listdir(cwd)
## Code gets the first sheet of a given file
df = pd.DataFrame()
for file in files:
if file.endswith('.xlsx'):
d = pd.read_excel(file)
d["filename"] = file
df = df.append(d, ignore_index=True)
df.head()
df.to_excel('Combined.xlsx')
uj5u.com熱心網友回復:
創建一個 dict 來收集您的資料幀,然后在匯出之前將它們組合起來(并使用pathlib而不是os模塊):
import pathlib
import pandas as pd
data = {}
for file in pathlib.Path().glob('*.xlsx'):
data[file.name] = pd.read_excel(file)
pd.concat(data).to_excel('Combined.xlsx')
注意:如果您想獲取沒有擴展名的檔案名,請使用file.stem而不是file.name.
uj5u.com熱心網友回復:
試試這個。
import os
import pandas as pd
cwd = os.path.abspath('')
files = os.listdir(cwd)
## Code gets the first sheet of a given file
df = pd.DataFrame()
for file in files:
if file.endswith('.xlsx'):
df = df.append([file]) # Here is the code to ADD filename
df = df.append(pd.read_excel(file), ignore_index=True)
df.head()
df.to_excel('Combined.xlsx')
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/341107.html
