约定:
import pandas as pd
import numpy as np
import sys
写入CSV文件
写入csv文件是最常用的,csv文件默认用’,’作为分隔符。
df1.to_csv(path_or_buf=None, sep=’,’, na_rep=”, float_format=None, columns=None, header=True, index=True, index_label=None, mode=’w’, encoding=None)
常用参数解释:
path_or_buf:文件名、文件具体、相对路径、文件流等
sep:文件分割符号
na_rep:将NaN转换为特定值
columns:选择部分列写入
header:忽略列名
index:False则选择不写入索引
df1=pd.DataFrame({'A':range(3),'B':list("abc"),'C':['red',np.NaN,'yellow']})
print(df1)
代码结果:
A B C
0 0 a red
1 1 b NaN
2 2 c yellow
1 写入时指定分隔符
to_csv()的sep默认为’,’,可指定任意字符作为分隔符
df1.to_csv(sys.stdout,sep='-')
代码结果:
-A-B-C
0-0-a-red
1-1-b-
2-2-c-yellow
2 将NaN转为特定字符串
写入时NaN会被表示为空字符串,我们可能希望用其他值代替
df1.to_csv(sys.stdout,na_rep='NULL')
代码结果:
,A,B,C
0,0,a,red
1,1,b,NULL
2,2,c,yellow
3 不写入列名
df1.to_csv(sys.stdout,header=None)
代码结果:
0,0,a,red
1,1,b,
2,2,c,yellow
4 不写入索引
df1.to_csv(sys.stdout,index=False)
代码结果:
A,B,C
0,a,red
1,b,
2,c,yellow
5 保留部分列且排序
df1.to_csv(sys.stdout,columns=['B','A'])
代码结果:
,B,A
0,a,0
1,b,1
2,c,2
写入Excel文件
对比写入csv文件,写入Excel文件不同的就是,当需要写入多个Sheet时,则需要在写入前创建一个Excel文件。
df1.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)
常用参数解释:
excel_writer:文件名、文件具体、相对路径、文件对象等
sheet_name:写入时设定Sheetname,默认为’Sheet1’
sep:文件分割符号
na_rep:将NaN转换为特定值
columns:选择部分列写入
header:忽略列名
index:False则选择不写入索引
1 写入单个Sheet表格
只能写入一个Sheet表格,多次写入则会清除excel文件中的内容
df1.to_excel('df1.xlsx')
2 指定Sheetname
df1.to_excel('df1.xlsx',sheet_name='df1')
3 同一个Excel文件写入多个Sheet表格
写入多个表时,需要用到pd.ExcelWriter()打开一个Excel文件
work=pd.ExcelWriter('df2.xlsx')
df1.to_excel(work,sheet_name='df2')
df1['A'].to_excel(work,sheet_name='df3')
谢谢大家的浏览,
希望我的努力能帮助到您,
共勉!