将多个文件合并到单个datafram中

2024-04-26 17:32:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个代码来读取多个文件,格式化数据并将它们合并到一个数据帧中:

import os.path
import glob

def get_merged_file(flist, **kwargs):
    fdf=pd.DataFrame()
    for f in flist:
        df=pd.read_excel(f, **kwargs)
        df=df.iloc[4:-1]
        df.columns=df.iloc[0]
        df=df.iloc[1:].reset_index(drop=True)
        df = df.iloc[:, :-4]
        fdf.append(df)
    return fdf

path='S:/random path'

fls = os.path.join(path, 'Report*.xls')

dff = get_merged_file(glob.glob(fls))
print(dff)

但这又回来了

空数据帧

列:[]

索引:[]

任何帮助都将不胜感激。你知道吗


Tags: 数据pathimportdfgetosmergedglob
1条回答
网友
1楼 · 发布于 2024-04-26 17:32:16

我认为最好让一个函数返回一个经过解析的数据帧,并使用pd.concat将它们放在一起。你知道吗

import os.path
import glob

def get_file(fp, **kwargs):
    df = pd.read_excel(f, **kwargs)
    df = df.iloc[4:-1]
    df.columns = df.iloc[0]
    df = df.iloc[1:].reset_index(drop=True)
    df = df.iloc[:, :-4]
    return df

path='S:/random path'

fls = os.path.join(path, 'Report*.xls')

dff = pd.concat([get_file(f) for f in glob.glob(fls)])
print(dff)

相关问题 更多 >