小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

pandas 讀寫 Excel

 閑讀古書 2020-03-15

pandas 讀寫 Excel,可以用于將重復(fù)的數(shù)據(jù)加工工作交給 pandas,節(jié)省手工勞動(dòng),使用起來(lái)也比較方便,但輸出的格式并不太美觀。本文介紹 read_excel()to_excel() 的部分細(xì)節(jié),同時(shí)探討如何輸出一個(gè)較為美觀的 Excel 工作表。

pandas 讀取 Excel 文件

語(yǔ)法

DataFrame.read_excel() 的語(yǔ)法:

pandas.read_excel(io, 
                  sheet_name=0, 
                  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, 
                  skip_footer=0, 
                  skipfooter=0, 
                  convert_float=True, 
                  mangle_dupe_cols=True, 
                  **kwds)

參數(shù)和返回值的說(shuō)明請(qǐng)參考 pandas 文檔

最簡(jiǎn)單的用法,只需要指定文件名參數(shù),支持 xls 文和 xlsx 文件格式,函數(shù)的返回值為 DataFrame 類型的對(duì)象。比如讀取 D 盤根目錄下的 source.xlsx 文件:

import pandas as pd
df1 = pd.read_excel(r'D:/source.xlsx)

如果想讀取 py 文件所在目錄下的某個(gè) Excel 文件,可以參考下面的代碼:

import pandas as pd 
import os

# get path of current directory
curr_path = os.path.dirname(os.path.abspath(__file__))
fname = os.path.join(curr_path, 'users.xlsx')
df2 = pd.read_excel(fname)

指定要讀取的工作表

對(duì)于有多個(gè)工作表的 Excel 文件,pandas 默認(rèn)讀取第一個(gè)工作表( sheet_name=0 )。通過(guò)如下兩種方法可以指定要讀取的工作表:

# 方法一:通過(guò) index 指定工作表
df3 = pd.read_excel(file_name, sheet_name=0)

# 方法二:指定工作表名稱
df4 = pd.read_excel(file_name, sheet_name='Sheet1')

導(dǎo)入指定列

如果只想導(dǎo)入指定的列,通過(guò) usecols 參數(shù),比如想導(dǎo)入 A:DH 這 4 列,有如下兩種方法:

df6 = pd.read_excel(r'D:/source.xlsx', usecols='A:D,H')

# 或者
df6 = pd.read_excel(r'D:/source.xlsx', usecols=[0,1,2,3,7])

指定表頭

默認(rèn)情況下,pandas 假定第一行為表頭 (header),如果 Excel 不是從第一行開始,header 參數(shù)用于指定將哪一行作為表頭,表頭在 DataFrame 中變成列索引 (column index) ,header 參數(shù)從 0 開始,比如第二行作為 header,則:

df = pd.read_excel(file_name, header=1)

pandas 寫入 Excel

語(yǔ)法

DataFrame.to_excel() 的語(yǔ)法:

DataFrame.to_excel(excel_writer, 
                   sheet_name='Sheet1', 
                   na_rep='', 
                   float_format=None, 
                   columns=None, 
                   header=True, 
                   index=True, 
                   index_label=None, 
                   startrow=0, startcol=0, 
                   engine=None, 
                   merge_cells=True, 
                   encoding=None, 
                   inf_rep='inf', 
                   verbose=True, 
                   freeze_panes=None)

參數(shù)和返回值的說(shuō)明請(qǐng)參考 pandas 文檔 。

數(shù)據(jù)寫入 Excel,需要首先安裝一個(gè) engine,由 engine 負(fù)責(zé)將數(shù)據(jù)寫入 Excel,pandas 使用 openpyx 或 xlsxwriter 作為寫入引擎。

要將單一對(duì)象寫入 Excel,只需要指定 file name 即可:

import pandas as pd
import os

path = os.path.dirname(os.path.abspath(__file__))
source_file = os.path.join(path, 'source.xlsx')
output_file = os.path.join(path, 'output.xlsx')

df = pd.read_excel(source_file, sheet_name=0)
df.to_excel(output_file)

如果 output.xlsx 文件已經(jīng)存在,to_excel()先刪除 output.xlsx 文件,然后重新生成一個(gè)新的文件,并且默認(rèn)添加一個(gè)索引列,索引為從 0 到 n 的整數(shù)。

不使用索引

導(dǎo)出 Excel,一般不需要索引,將 index 參數(shù)設(shè)為 False 即可:

df.to_excel(output_file, index=False)

多工作表導(dǎo)出

導(dǎo)出多個(gè)工作表需要明確給出 excel writer engine,然后調(diào)用 DataFrame.to_excel()方法:

import pandas as pd
import os

path = os.path.dirname(os.path.abspath(__file__))
source_file = os.path.join(path, 'source.xlsx')
output_file = os.path.join(path, 'output.xlsx')

df1 = pd.read_excel(source_file, sheet_name=0)
df2 = pd.read_excel(source_file, sheet_name=0, usecols='A:D,H')

with pd.ExcelWriter(output_file, engine='xlsxwriter') as writer:    
    df1.to_excel(writer, sheet_name='Sheet1', index=False)
    df2.to_excel(writer, sheet_name='Sheet2', index=False)

工作表美化

pandas 導(dǎo)出的工作表并不美觀,如果想對(duì)工作表進(jìn)行美化的話,可在 to_excel()方法之后,通過(guò)Excel writer engine 的格式設(shè)置的功能來(lái)設(shè)置格式。根據(jù)測(cè)試, to_excel() 因?yàn)橄葎h除文件,所以也不能使用 Template 來(lái)保存預(yù)定義格式。所以如果需要導(dǎo)出有格式的 Excel 文件,比如作為報(bào)表輸出,可考慮 Template + Excel writer engine 手工代碼的方式。

Creating Advanced Excel Workbooks with Python 這篇文章講到了一個(gè)方法,使用 xlsxwriter 的 add_table() 方法,在 Excel 中創(chuàng)建一個(gè) Table 對(duì)象(中文經(jīng)常被稱為智能表格),然后選擇一個(gè)預(yù)定義的格式。我對(duì)代碼進(jìn)行了加工,使之更具普適性:

import pandas as pd
import os

def get_col_widths(dataframe):    
    return [max([len(str(s))  for s in dataframe[col].values] 
            + [len(col)]) for col in dataframe.columns]

def fmt_excel(writer, sheetname, dataframe):
    # Get the workbook and the summary sheet so we can add the formatting
    workbook = writer.book
    worksheet = writer.sheets[sheetname]
    col_count = dataframe.shape[1]
    row_count = dataframe.shape[0]

    col_names = []
    for i in range(0, col_count):
        col_names.append({'header': dataframe.columns[i]})

    # rng = 'A1:H{}'.format(row_count + 1)
    worksheet.add_table(0, 0, row_count,col_count-1, {
        'columns': col_names,
        'style': 'Table Style Medium 20'
    })

    # auto column size
    col_widths = get_col_widths(dataframe)
    for i, width in enumerate(col_widths):
        worksheet.set_column(i, i, width)

path = os.path.dirname(os.path.abspath(__file__))
source_file = os.path.join(path, 'source.xlsx')
output_file = os.path.join(path, 'output.xlsx')

df = pd.read_excel(source_file, sheet_name=0)

writer = pd.ExcelWriter(output_file, engine='xlsxwriter')
df.to_excel(writer, 'Sheet1', index=False)

fmt_excel(writer, 'Sheet1', df)
writer.save()

參考

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多