1

我有一个包含 10 个工作表的 excel 文件。有些工作表有数据,有些是空的,但这会定期更改,包括第一个和/或最后一个工作表。

使用 Python 2.7,我正在做的是将所有工作表加载到 pandas df 中以在另一个函数中处理。我还添加了一个带有工作表名称的列。加载工作表似乎工作正常,但我的一列有 14-20 个字符的值,以 0 结尾。所以当我打印出 dict 时,它们看起来是正确的,但是 pandas 正在转换为 sci 表示法,我不知道如何保留这些值。

这是一些字典数据:

           API_NUM        NAME         DATE_START DATE_FINISH  SH_NAME
0   12345678910000   RAYES A - 1       2018-07-28  2018-08-25   Andy
1   12345678900000   RAYES A - 2       2018-07-28  2018-08-25   Mine
2   23456789090000   RAYES A - 3       2018-07-28  2018-08-25   Shef
3   34567890600000   RAYES A - 4       2018-07-28  2018-08-25   Mary
4   45678901220000   RAYES A - 5       2018-07-28  2018-08-25   Tom 

所以当我读入下面的数据时,它加载得很好

excel_file ='my path to a xlsx'
sheets_dict = pd.read_excel(excel_file, sheet_name=None)
full_table = pd.DataFrame()
for name, sheet in sheets_dict.items():
    sheet['SH_NAME'] = name
    sheet = sheet.rename(columns=lambda x: x.split('\n')[-1])
    full_table = full_table.append(sheet)
full_table.reset_index(inplace=True, drop=True)

印刷

sheets_dict 

API_NUM 看起来应该是这样,但 full_table 科学记下了这个数字。

但是——这终究还是奏效了——

full_table['API_NUM'] = full_table['API_NUM'].map(lambda x: '{:.0f}'.format(x))


           API_NUM        NAME         DATE_START DATE_FINISH  SH_NAME
0        1234567891    RAYES A - 1       2018-07-28  2018-08-25   Andy
1        123456789     RAYES A - 2       2018-07-28  2018-08-25   Mine
2        2345678909    RAYES A - 3       2018-07-28  2018-08-25   Shef
3        3456789060    RAYES A - 4       2018-07-28  2018-08-25   Mary
4        4567890122    RAYES A - 5       2018-07-28  2018-08-25   Tom 



当我将值转换为字符串时,它们变成 -2147483648

将 df 写入 csv,该列删除了尾随的 0。

问题是,稍后在另一个函数中,我创建了这些值的字符串列表来执行 sql 查询。所以后来,它看起来像:

myTableValue IN ('12345678910000', '12345678900000', '23456789090000', '34567890600000', '45678901220000') 

我正在运行查询的字段是一个字符串字段。




编辑:我相信 lambda 函数毕竟最终会起作用,这是一个糟糕的数据和我自己给我带来问题的案例。因此,该方法或以下方法将起作用。这对于想要使用 Python 将工作表合并到 df 中的人可能会有所帮助

4

1 回答 1

1

好吧,解决我自己的帖子。似乎有效的是加载工作表的不同方法。现在我相信你们中的一位大师会知道为什么这有效而上述方法没有,但无论如何对于任何想要使用它的人来说,这种方式都更简单。

import xlrd

excel = 'path to my file'
book = xlrd.open_workbook(excel)


# get a list of work sheet names
sheetlist = []
for sheet in book.sheet_names():
    sheetlist.append(sheet)

# create and ordered dict of the worksheets
dfs = pd.read_excel(excel, sheetname=sheetlist)

df = pd.concat((df.assign(source=sheet) for sheet, df in dfs.items()), ignore_index=True)
df['API_NUM'] = df['API_NUM'].astype(str)
于 2018-07-31T20:49:20.763 回答