【python】pandas庫pd.to_excel操作寫入excel文件參數整理與實例

excel的寫入函數爲pd.DataFrame.to_excel();必須是DataFrame寫入excel, 即Write DataFrame to an excel sheet。

to_excel(self, 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)

常用參數解析

  • excel_writer : ExcelWriter目標路徑
In [16]: df = pd.read_csv('test.csv')

In [17]: df
Out[17]:
   index  a_name  b_name
0      0       1       3
1      1       2       3
2      2       3       4
#excel_writer :'excel_output.xls'輸出路徑
In [18]: df.to_excel('excel_output.xls')
  • sheet_name :excel表名命名
#得到的表名就是'biubiu'
In [20]: df.to_excel('excel_output.xls',sheet_name='biubiu')
  • na_rep : 缺失值填充 ,可以設置爲字符串
In [25]: df = pd.read_excel('excel_output.xls')

In [26]: df
Out[26]:
   index  a_name  b_name
0      0       1     3.0
1      1       2     3.0
2      2       3     NaN
#如果na_rep設置爲bool值,則寫入excel時改爲0和1;也可以寫入字符串或數字
In [27]: df.to_excel('excel_output.xls',na_rep=True)

In [28]: pd.read_excel('excel_output.xls')
Out[28]:
   index  a_name  b_name
0      0       1       3
1      1       2       3
2      2       3       1

In [29]: df.to_excel('excel_output.xls',na_rep=False)

In [30]: pd.read_excel('excel_output.xls')
Out[30]:
   index  a_name  b_name
0      0       1       3
1      1       2       3
2      2       3       0

In [31]: df.to_excel('excel_output.xls',na_rep=11)

In [32]: pd.read_excel('excel_output.xls')
Out[32]:
   index  a_name  b_name
0      0       1       3
1      1       2       3
2      2       3      11
  • columns :選擇輸出的的列存入
In [44]: df.to_excel('excel_output.xls',na_rep=11,columns=['index'])

In [45]: pd.read_excel('excel_output.xls')
Out[45]:
   index
0      0
1      1
2      2
  • header :指定作爲列名的行,默認0,即取第一行,數據爲列名行以下的數據;若數據不含列名,則設定 header = None
In [48]: df.to_excel('excel_output.xls',na_rep=11,index=False)

In [49]: pd.read_excel('excel_output.xls')
Out[49]:
   index  a_name  b_name
0      0       1       3
1      1       2       3
2      2       3      11

In [50]: df.to_excel('excel_output.xls',na_rep=11,index=False,header=None)

In [51]: pd.read_excel('excel_output.xls')
Out[51]:
   0  1   3
0  1  2   3
1  2  3  11
  • index:默認爲True,顯示index,當index=False 則不顯示行索引(名字)
  • index_label:設置索引列的列名
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章