5種常用格式的數(shù)據(jù)輸出,手把手教你用Pandas實(shí)現(xiàn)
導(dǎo)讀:任何原始格式的數(shù)據(jù)載入DataFrame后,都可以使用類似DataFrame.to_csv()的方法輸出到相應(yīng)格式的文件或者目標(biāo)系統(tǒng)里。本文將介紹一些常用的數(shù)據(jù)輸出目標(biāo)格式。

df.to_csv('done.csv')
df.to_csv('data/done.csv') # 可以指定文件目錄路徑
df.to_csv('done.csv', index=False) # 不要索引# 創(chuàng)建一個(gè)包含out.csv的壓縮文件out.zip
compression_opts = dict(method='zip',
archive_name='out.csv')
df.to_csv('out.zip', index=False,
compression=compression_opts)
# 導(dǎo)出,可以指定文件路徑
df.to_excel('path_to_file.xlsx')
# 指定sheet名,不要索引
df.to_excel('path_to_file.xlsx', sheet_name='Sheet1', index=False)
# 指定索引名,不合并單元格
df.to_excel('path_to_file.xlsx', index_label='label', merge_cells=False)# 將多個(gè)df分不同sheet導(dǎo)入一個(gè)Excel文件中
with pd.ExcelWriter('path_to_file.xlsx') as writer:
df1.to_excel(writer, sheet_name='Sheet1')
df2.to_excel(writer, sheet_name='Sheet2')# 指定操作引擎
df.to_excel('path_to_file.xlsx', sheet_name='Sheet1', engine='xlsxwriter')
# 在'engine'參數(shù)中設(shè)置ExcelWriter使用的引擎
writer = pd.ExcelWriter('path_to_file.xlsx', engine='xlsxwriter')
df.to_excel(writer)
writer.save()
# 設(shè)置系統(tǒng)引擎
from pandas import options # noqa: E402
options.io.excel.xlsx.writer = 'xlsxwriter'
df.to_excel('path_to_file.xlsx', sheet_name='Sheet1')print(df.to_html())
print(df.to_html(columns=[0])) # 輸出指定列
print(df.to_html(bold_rows=False)) # 表頭不加粗
# 表格指定樣式,支持多個(gè)
print(df.to_html(classes=['class1', 'class2']))# 需要安裝SQLAlchemy庫(kù)
from sqlalchemy import create_engine
# 創(chuàng)建數(shù)據(jù)庫(kù)對(duì)象,SQLite內(nèi)存模式
engine = create_engine('sqlite:///:memory:')
# 取出表名為data的表數(shù)據(jù)
with engine.connect() as conn, conn.begin():
data = pd.read_sql_table('data', conn)
# data
# 將數(shù)據(jù)寫(xiě)入
data.to_sql('data', engine)
# 大量寫(xiě)入
data.to_sql('data_chunked', engine, chunksize=1000)
# 使用SQL查詢
pd.read_sql_query('SELECT * FROM data', engine)print(cdf.to_markdown())
'''
| | x | y | z |
|:---|----:|----:|----:|
| a | 1 | 2 | 3 |
| b | 4 | 5 | 6 |
| c | 7 | 8 | 9 |
'''


評(píng)論
圖片
表情
