Pandas dataframe数据写入文件和数据库

转自:http://www.dcharm.com/?p=584

Pandas是Python下一个开源数据分析的库,它提供的数据结构DataFrame极大的简化了数据分析过程中一些繁琐操作,DataFrame是一张多维的表,大家可以把它想象成一张Excel表单或者Sql表。之前这篇文章已经介绍了从各种数据源将原始数据载入到dataframe中,这篇文件介绍怎么将处理好的dataframe中的数据写入到文件和数据库中。
首先我们通过二维ndarray创建一个简单的DataFrame:

1
2
3
4
5
6
7
8
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文件

1
df .to_csv( 'D:\\a.csv' , sep= ',' , header=True, index=True)

第一个参数是说把dataframe写入到D盘下的a.csv文件中,参数sep表示字段之间用’,’分隔,header表示是否需要头部,index表示是否需要行号。
2. Dataframe写入到json文件

1
df .to_json( 'D:\\a.json' )

把dataframe写入到D盘下的a.json文件中,文件的内容为

1
{ "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}}

3.Dataframe写入到html文件

1
df .to_html( 'D:\\a.html' )

把dataframe写入到D盘下的a.html文件中,文件的内容为

1
< table border = "1" class = "dataframe" >\n  < thead >\n    < tr style = "text-align: right;" >\n      < th ></ th >\n      < th >0</ th >\n      < th >1</ th >\n      < th >2</ th >\n      < th >3</ th >\n    </ tr >\n  </ thead >\n  < tbody >\n    < tr >\n      < th >0</ th >\n      < td >1.049229</ td >\n      < td >-0.792261</ td >\n      < td >0.020418</ td >\n      < td >-1.664982</ td >\n    </ tr >\n    < tr >\n      < th >1</ th >\n      < td >0.348525</ td >\n      < td >-2.117607</ td >\n      < td >1.466823</ td >\n      < td >-0.924921</ td >\n    </ tr >\n    < tr >\n      < th >2</ th >\n      < td >1.307357</ td >\n      < td >-0.735035</ td >\n      < td >0.285608</ td >\n      < td >-0.905348</ td >\n    </ tr >\n  </ tbody >\n</ table >

在浏览器中打开a.html的样式为
table
4.Dataframe写入到剪贴板中
这个是我认为最为贴心的功能, 一行代码可以将dataframe的内容导入到剪切板中,然后可以复制到任意地方

1
df .to_clipboard()

5.Dataframe写入到数据库中

1
df .to_sql( 'tableName' , con=dbcon, flavor= 'mysql' )

第一个参数是要写入表的名字,第二参数是sqlarchmy的数据库链接对象,第三个参数表示数据库的类型,“mysql”表示数据库的类型为mysql。

转载于:https://www.cnblogs.com/lj821022/p/8232764.html

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值