pandas.DataFrame寫入數(shù)據(jù)庫的實(shí)現(xiàn)方式
pandas.DataFrame寫入數(shù)據(jù)庫的方式
以mysql數(shù)據(jù)庫為例,需要導(dǎo)入包pymysql。
假設(shè)我們已經(jīng)創(chuàng)建了一個(gè)df,現(xiàn)在將其導(dǎo)入數(shù)據(jù)庫中。
寫法如下:
import pymysql
import pandas as pd
from sqlalchemy import create_engine
#建立連接,username替換為用戶名,passwd替換為密碼,test替換為數(shù)據(jù)庫名
conn = create_engine('mysql+pymysql://username:passwd@localhost:3306/test',encoding='utf8') ?
#寫入數(shù)據(jù),table_name為表名,‘replace'表示如果同名表存在就替換掉
pd.io.sql.to_sql(df, "table_name", conn, if_exists='replace')Pandas DataFrame數(shù)據(jù)寫入文件和數(shù)據(jù)庫
Pandas是Python下一個(gè)開源數(shù)據(jù)分析的庫,它提供的數(shù)據(jù)結(jié)構(gòu)DataFrame極大的簡化了數(shù)據(jù)分析過程中一些繁瑣操作,DataFrame是一張多維的表,大家可以把它想象成一張Excel表單或者Sql表。
之前這篇文章已經(jīng)介紹了從各種數(shù)據(jù)源將原始數(shù)據(jù)載入到dataframe中,這篇文件介紹怎么將處理好的dataframe中的數(shù)據(jù)寫入到文件和數(shù)據(jù)庫中。
創(chuàng)建DataFrame對象
首先我們通過二維ndarray創(chuàng)建一個(gè)簡單的DataFrame:
import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(3, 4)) df
0 1 2 3 0 1.0492286140081302 -0.7922606407983686 0.020418054868760225 -1.6649819403741724 1 0.3485250628814134 -2.117606544377745 1.466822878437205 -0.9249205656243358 2 1.3073567907490637 -0.7350348086218035 0.2856083175408006 -0.9053483976251634
1. Dataframe寫入到csv文件
df.to_csv('D:\\a.csv', sep=',', header=True, index=True)第一個(gè)參數(shù)是說把dataframe寫入到D盤下的a.csv文件中,參數(shù)sep表示字段之間用’,’分隔,header表示是否需要頭部,index表示是否需要行號(hào)。
2. Dataframe寫入到j(luò)son文件
df.to_json('D:\\a.json')把dataframe寫入到D盤下的a.json文件中,文件的內(nèi)容為
{"0":{"0":1.049228614,"1":0.3485250629,"2":1.3073567907},"1":{"0":-0.7922606408,"1":-2.1176065444,"2":-0.7350348086},"2":{"0":0.0204180549,"1":1.4668228784,"2":0.2856083175},"3":{"0":-1.6649819404,"1":-0.9249205656,"2":-0.9053483976}}官方demo:
df = pd.DataFrame([['a', 'b'], ['c', 'd']],
? ? ? ? ? ? ? ? ? ?index=['row 1', 'row 2'],
? ? ? ? ? ? ? ? ? ?columns=['col 1', 'col 2'])
###########
split
###########
df.to_json(orient='split')
>'{"columns":["col 1","col 2"],
? "index":["row 1","row 2"],
? "data":[["a","b"],["c","d"]]}'
###########
index
###########
df.to_json(orient='index')
>'{"row 1":{"col 1":"a","col 2":"b"},"row 2":{"col 1":"c","col 2":"d"}}'
###########
records
###########
df.to_json(orient='records')
>'[{"col 1":"a","col 2":"b"},{"col 1":"c","col 2":"d"}]'
###########
table
###########
df.to_json(orient='table')
>'{"schema": {"fields": [{"name": "index", "type": "string"},
? ? ? ? ? ? ? ? ? ? ? ? {"name": "col 1", "type": "string"},
? ? ? ? ? ? ? ? ? ? ? ? {"name": "col 2", "type": "string"}],
? ? ? ? ? ? ?"primaryKey": "index",
? ? ? ? ? ? ?"pandas_version": "0.20.0"},
? "data": [{"index": "row 1", "col 1": "a", "col 2": "b"},
? ? ? ? ? ?{"index": "row 2", "col 1": "c", "col 2": "d"}]}'3.Dataframe寫入到html文件
df.to_html('D:\\a.html')把dataframe寫入到D盤下的a.html文件中,文件的內(nèi)容為
<table border="1" class="dataframe"> ? <thead> ? ? <tr style="text-align: right;"> ? ? ? <th></th> ? ? ? <th>0</th> ? ? ? <th>1</th> ? ? ? <th>2</th> ? ? ? <th>3</th> ? ? </tr> ? </thead> ? <tbody> ? ? <tr> ? ? ? <th>0</th> ? ? ? <td>-0.677090</td> ? ? ? <td>0.990133</td> ? ? ? <td>-1.775863</td> ? ? ? <td>0.654884</td> ? ? </tr> ? ? <tr> ? ? ? <th>1</th> ? ? ? <td>-1.825927</td> ? ? ? <td>-2.262985</td> ? ? ? <td>-0.849212</td> ? ? ? <td>-0.154182</td> ? ? </tr> ? ? <tr> ? ? ? <th>2</th> ? ? ? <td>0.252012</td> ? ? ? <td>0.464503</td> ? ? ? <td>0.771977</td> ? ? ? <td>0.329159</td> ? ? </tr> ? </tbody> </table>
在瀏覽器中打開a.html的樣式為
4.Dataframe寫入到剪貼板中
這個(gè)是我認(rèn)為最為貼心的功能, 一行代碼可以將dataframe的內(nèi)容導(dǎo)入到剪切板中,然后可以復(fù)制到任意地方
df.to_clipboard()
5.Dataframe寫入到數(shù)據(jù)庫中
df.to_sql('tableName', con=dbcon, flavor='mysql')第一個(gè)參數(shù)是要寫入表的名字,第二參數(shù)是sqlarchmy的數(shù)據(jù)庫鏈接對象,第三個(gè)參數(shù)表示數(shù)據(jù)庫的類型,“mysql”表示數(shù)據(jù)庫的類型為mysql。
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python實(shí)現(xiàn)Microsoft Office自動(dòng)化的幾種方式及對比詳解
辦公自動(dòng)化是指利用現(xiàn)代化設(shè)備和技術(shù),代替辦公人員的部分手動(dòng)或重復(fù)性業(yè)務(wù)活動(dòng),優(yōu)質(zhì)而高效地處理辦公事務(wù),實(shí)現(xiàn)對信息的高效利用,進(jìn)而提高生產(chǎn)率,實(shí)現(xiàn)輔助決策的目的,所以本文給大家介紹了Python實(shí)現(xiàn)Microsoft Office自動(dòng)化的幾種方式,需要的朋友可以參考下2025-03-03
Python文件操作JSON CSV TSV Excel和Pickle文件序列化
這篇文章主要為大家介紹了Python文件操作之JSON、CSV、TSV、Excel和Pickle文件序列化示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11
Python正則表達(dá)式在數(shù)據(jù)處理中的應(yīng)用實(shí)戰(zhàn)案例
正則表達(dá)式是一種用于匹配字符串的模式,它由普通字符和特殊字符組成,通過定義這些模式,我們可以快速查找、替換或提取文本中的特定內(nèi)容,這篇文章主要介紹了Python正則表達(dá)式在數(shù)據(jù)處理中應(yīng)用實(shí)戰(zhàn)的相關(guān)資料,需要的朋友可以參考下2025-10-10
Python中使用PyHook監(jiān)聽鼠標(biāo)和鍵盤事件實(shí)例
這篇文章主要介紹了Python中使用PyHook監(jiān)聽鼠標(biāo)和鍵盤事件實(shí)例,這個(gè)庫依賴于另一個(gè)Python庫PyWin32,并且只能運(yùn)行在Windows平臺(tái),需要的朋友可以參考下2014-07-07

