python - 将 Excel 读入数据框并将文件名保留为列(Pandas)

标签 python pandas

我正在尝试将多个 Excel 文件读入数据框中,但我似乎找不到一种方法将文件名保留为一列来引用它的来源。另外,我需要在执行 read_excel 之前过滤 Excel 文件的名称和创建日期。 (文件太多了,如果不需要的话我不想读)这就是我所拥有的:

res = []
for root, dirs, files in os.walk('.../Minutes/', topdown=True):
    if len(files) > 0:
        res.extend(zip([root]*len(files), files))

df = pd.DataFrame(res, columns=['Path', 'File_Name'])

df['FullDir'] = df.Path+'\\'+df.File_Name

list_ = []
for f in df["FullDir"]:
    data = pd.read_excel(f, sheet_name = 1)
    list_.append(data)
    df2 = pd.concat(list_)

df2

我想要什么作为输出

   A  B  filename  File Date Created
0  a  a  File1     1-1-2018
1  b  b  File1     1-1-2018
2  c  c  FIle2     2-1-2018
3  a  a  File2     2-1-2018

任何帮助将不胜感激!!

最佳答案

您可以将 concatkeys 一起使用,然后使用 reset_index

res = []
for root, dirs, files in os.walk('.../Minutes/', topdown=True):
    if len(files) > 0:
        res.extend(zip([root]*len(files), files))

df = pd.DataFrame(res, columns=['Path', 'File_Name'])

df['FullDir'] = df.Path+'\\'+df.File_Name

假设上述代码按预期工作

list_ = []
for f in df["FullDir"]:
    data = pd.read_excel(f, sheet_name = 1)
    list_.append(data)

df2 = pd.concat(list_, keys=df.File_Name.values.tolist()).reset_index(level=0)

关于python - 将 Excel 读入数据框并将文件名保留为列(Pandas),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50668319/

相关文章:

python - pandas 方法的有效参数

python - 查找满足聚合条件的最小连续 pandas 行集

python-3.x - 数据框连接列

Python 分组转置

python - 在 Pandas 中每行创建一个唯一值?

python - 如果默认列中的行为 NaN,如何从数据框中的其他列中选择行?

python - 如何在 Python 2.6 中使用 Numerical Python

python - Pandas:聚合嵌套字典的 python 列表中的最小值、平均值和最大值

python - 在 python 中获取 gif 的每秒帧数?

python imaplib 意外响应 220