【问题标题】:How to export to multiple excel sheet of a single csv file through pandas in python如何通过python中的pandas导出到单个csv文件的多个excel表
【发布时间】:2020-01-29 08:59:58
【问题描述】:

我在 python pandas 中导入了一个大的 txt 文件。现在我想将 csv 文件导出到多个 excel,因为数据太大而无法放入单个 excel 表中。

我使用以下命令:

import pandas as pd
df = pd.read_csv('basel.txt',delimiter='|')
df.to_excel('basel.txt')

不幸的是,我收到了以下错误:

****ValueError: This sheet is too large! Your sheet size is: 1158008, 18 Max sheet size is: 1048576, 16384****

【问题讨论】:

标签: python excel pandas dataframe


【解决方案1】:

您可以分成多个块并将每个块写在一张纸上。 np.array_split 分成若干块 np.split 需要等分。

import numpy as np

nsheets = 10  # you may change it
for i, temp in enumerate(np.array_split(df, nsheets)):
    temp.to_excel('basel.xls', sheet_name=f'sheet_{i}')

【讨论】:

    【解决方案2】:
    import pandas as pd
    chunksize = 10 ** 6
    for chunk in pd.read_csv('basel.txt', chunksize=chunksize):
        chunk.to_excel('basel_'+str(chunk)+'.excel')
    

    您可以分块读取 pandas 文件并将每个块保存在 excel 文件中

    【讨论】:

      【解决方案3】:

      您可以将数据集的一半写入不同的 Excel 工作表:

      import pandas as pd
      df = pd.read_csv('basel.txt',delimiter='|')
      df.iloc[:df.shape[0]//2,:].to_excel('basel.xls', sheet_name='First Sheet')
      df.iloc[df.shape[0]//2:,:].to_excel('basel.xls', sheet_name='Second Sheet')
      

      【讨论】:

      • 使用上述代码后,出现如下错误:TypeError: to_excel() got an unexpected keyword argument 'sheet'
      • 对不起,应该是sheet_name
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-02
      • 1970-01-01
      • 1970-01-01
      • 2020-12-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多