Pandas ExcelFile将列读为字符串

时间:2018-03-19 22:01:21

标签: python pandas dataframe

我知道您可以使用pd.read_excel(如here所述)阅读Excel时指定数据类型。你可以使用pd.ExcelFile吗?

我有以下代码:

 if ".xls" in 
     xl = pd.ExcelFile(path + "\\" + name, )
     for sheet in xl.sheet_names:
         xl_parsed = xl.parse(sheet)

解析工作表时,列中的某些值以科学计数法显示。在加载之前我不知道列名,所以我需要将所有内容导入为字符串。理想情况下,我希望能够做xl_parsed = xl.parse(sheet, dtype = str)之类的事情。有什么建议吗?

2 个答案:

答案 0 :(得分:1)

如果您希望使用更清洁的解决方案,请使用以下内容:

excel = pd.ExcelFile(path)
for sheet in excel.sheet_names:
    columns = excel.parse(sheet).columns
    converters = {column: str for column in columns}

    data = excel.parse(sheet, converters=converters)

答案 1 :(得分:0)

我选择了roganjosh的建议 - 首先打开excel,获取列名,然后传递给转换器。

                    if ".xls" in name:
                        xl = pd.ExcelFile(path)
                        sheetCounter = 1
                            for sheet in xl.sheet_names:
                            ### Force to read as string ###
                            column_list = []
                            df_column = pd.read_excel(path, sheetCounter - 1).columns
                            for i in df_column:
                                column_list.append(i)
                            converter = {col: str for col in column_list}
                            ##################
                            xl_parsed = xl.parse(sheet, converters=converter)
                            sheetCounter = sheetCounter + 1