[Python] pandas Library pd.to_ Parameter arrangement and example of Excel operation writing into excel file

excel writes to pd. dataframe.to_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)

common parameter resolution

  • excel_writer: ExcelWriter target path
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 sheet name

#得到的表名就是'biubiu'
In [20]: df.to_excel('excel_output.xls',sheet_name='biubiu')
  • na_rep: missing value filled, can be set to the string
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时改为01;也可以写入字符串或数字
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: select the output columns to be stored.
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: specify the row as the column name, default 0, that is, take the first row, the data is the data below the column name row; If the data does not contain column names, set 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: defaults to True and displays index. When index=False, row index (name) is not displayed
  • index_label: sets the column name of index column

Read More: