如何使用熊猫python根据给定的ip地址将大型excel文件拆分为多个工作表

时间:2019-03-05 06:13:35

标签: python excel pandas

我是熊猫和python的新手,所以遇到了一些麻烦。我有一个大的excel文件,我需要使用python脚本将其分为多个工作表。我必须根据数据中给出的IP地址进行划分。我不知道该怎么做,不胜感激。 我之前不了解使用python或任何库的知识。这是我所做的,但是为每一行创建了工作簿。

import pandas as pd
df = pd.read_excel("D:/Users/Zakir/Desktop/MyNotebooks/Legacy.xls", sheet_name="Total", header=0, names=None, index_col=None, parse_cols=None, usecols=None, squeeze=False, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skiprows=None, nrows=None, na_values=None, keep_default_na=True, verbose=False, parse_dates=False, date_parser=None, thousands=None, comment=None, skipfooter=0, convert_float=True, mangle_dupe_cols=True)

writer = pd.ExcelWriter('D:/Users/Zakir/Desktop/MyNotebooks/pandas_simple.xlsx', engine='xlsxwriter')
for index, row in df.iterrows():
    df1 = df.iloc[[index]]
    df1.set_index('Number',inplace=True)
    df1.to_excel(writer,  sheet_name=row['IPAddress'])
writer.save()

This is the kind of excel file i have. over 5000 rows. There are 60 groups of ip addresses and have to divide each group into its own worksheet

2 个答案:

答案 0 :(得分:0)

如果您有足够的内存,请采用一种解决方案:

from pandas import ExcelWriter
df = pd.read_excel('file',sheet_name="Total", header=0, #other settings.....#)
writer = ExcelWriter('E:/output.xlsx',engine='xlsxwriter')
print(df)
def writesheet(g):
    a = g['IPAddress'].tolist()[0]
    g.to_excel(writer, sheet_name=str(a), index=False)# index = True if you want to keep index


df.groupby('IPAddress').apply(writesheet)
writer.save()

答案 1 :(得分:0)

这是我实现代码的方法,用于检查文件夹,遍历所有excel文件并按列名的值分割每个文件,假设文件中有一张纸,可以将其作为输入(vColName)传递: / p>

import sys
import os, shutil
from os import listdir
from os.path import isfile, join
import pandas as pd
import urllib as ul
import datetime
import xlrd

#this method retrieves all the xlsx filenames from a folder
def find_excel_filenames( path_to_dir, suffix=".xlsx" ):
    filenames = listdir(path_to_dir)
    return [ filename for filename in filenames if filename.endswith( suffix ) ]

#this folder contains .xlsx files
filePath = "D:\files\sample\"

#there is a subfolder in my solution to move the processed files to
#and another subfolder to move the splitted output files
archivePath = os.path.join(filePath, "archive")
outPath = os.path.join(filePath, "output")

#get a list of filenames
fnames = find_excel_filenames(filePath)

#loop through each file
for fl in fnames:
    vFile = os.path.join(filePath, fl)
    #load the content of the file to a data frame, 
    #I open the file twice, first to get the number of columns and
    #create the converter, then to open the file with string converter
    #it helps with trimming of leading zeros

    df = pd.read_excel(vFile, header=None)

    column_list = []
    for i in df:
        column_list.append(i)

    converter = {col: str for col in column_list} 

    df1 = pd.read_excel(vFile, converters=converter)
    colValues=df1[vColName].unique().tolist()

    for v in colValues:
        filteredDF = df1.loc[df1[vColName]==v]
        vOutFile = os.path.join(outPath, fl+''_''+v.replace("/"," ")+''.xlsx'')
        writer = pd.ExcelWriter(vOutFile, engine=''xlsxwriter'')
        # Convert the dataframe to an XlsxWriter Excel object.
        filteredDF.to_excel(writer, sheet_name=''Sheet1'')
        # Close the Pandas Excel writer and output the Excel file.
        writer.save()

    #move the processed file to an archive folder
    dst_file = os.path.join(archivePath, fl)
    if os.path.exists(dst_file):
        os.remove(dst_file)
    shutil.move(vFile, archivePath)