繁体   English   中英

apply() 应用于 ExcelFile、Pandas 的每个数据框的每一列

[英]apply() to every column of every dataframe of an ExcelFile, Pandas

我有一个包含多个工作表的 xlsx 文件。

我读了它并将工作表分成数据帧:

xls=pd.ExcelFile('path/to/multisheet_excelfile.xlsx')
dfs={sheet: pd.read_excel(xls,sheet) for i, sheet in enumerate(xls.sheet_names)}

我遍历数据帧,然后遍历行,以应用apply()

for df in dfs.values():
    for col in df.columns:
        df[col] = df[col].apply(lambda name:
                                            # apply some function here, let's say:
                                            re.sub("[\[].*?[\]]", "", repr(name)))

有没有更好的方法来做到这一点,可能不涉及双循环?

你不能没有循环,因为pandassheet创建DataFrame 但是你可以在 1 个循环中完成:

# {'sheet_name1': df1, 'sheet_name2': df2, ...}
dfs = pd.read_excel(xls, sheet_name=pd.ExcelFile('file_path').sheet_names)  # type: dict
dfs = {
    sheet_name: df.applymap(lambda x: re.sub("[\[].*?[\]]", "", repr(x))
    for sheet_name, df in dfs.items()
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM