亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用文件名作為數據框中的列標題

使用文件名作為數據框中的列標題

智慧大石 2023-05-23 10:24:22
我有多個 excel 文件,我需要將所有這些文件中的一列整理到一個數據框中。我使用了以下代碼:my_excel_files = glob.glob(r"C:\Users\......\Documents\*.xlsx")total_dataframe = pd.DataFrame() for file in my_excel_files:    df = pd.read_excel(file, header = 1)     new_df = df['Comments']    total_dataframe = pd.concat([total_dataframe, new_df], axis=1)此代碼從我所有的 excel 文件中獲取所有“評論”列,并將它們附加到 total_dataframe 中。問題是該數據框中的列都是“評論”,所以我無法區分每一列的來源。有沒有辦法使用每個 excel 的完整文件名作為列標題,這樣我就知道每個列來自哪個 excel
查看完整描述

1 回答

?
喵喔喔

TA貢獻1735條經驗 獲得超5個贊

您可以使用或列表理解創建系列列表append,然后keys在中使用參數concat

import glob, os


my_excel_files = glob.glob(r"C:\Users\......\Documents\*.xlsx")

names = [os.path.basename(f).split('.')[0] for f in my_excel_files]


output = []

for file in my_excel_files:

? ? df = pd.read_excel(file, header = 1)?

? ? new_df = df['Comments']

? ? output.append(new_df)


final = pd.concat(output, axis=1, keys=names)

或者:


import glob, os


my_excel_files = glob.glob(r"C:\Users\......\Documents\*.xlsx")

names = [os.path.basename(f).split('.')[0] for f in my_excel_files]


output = [pd.read_excel(file, header = 1)['Comments']? for file in my_excel_files]

final = pd.concat(output, axis=1, keys=names)


查看完整回答
反對 回復 2023-05-23
  • 1 回答
  • 0 關注
  • 161 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號