为了账号安全,请及时绑定邮箱和手机立即绑定

使用文件名作为数据框中的列标题

使用文件名作为数据框中的列标题

智慧大石 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 关注
  • 137 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信