mirror of
https://github.com/redoules/redoules.github.io.git
synced 2025-12-12 15:59:34 +00:00
388 lines
17 KiB
HTML
388 lines
17 KiB
HTML
<!DOCTYPE html>
|
|
<html lang="fr">
|
|
|
|
<head>
|
|
<meta charset="utf-8">
|
|
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
|
|
<meta name="description" content="Data Science for Political and Social Phenomena">
|
|
<meta name="author" content="Guillaume Redoulès">
|
|
<link rel="icon" href="../favicon.ico">
|
|
|
|
<title>Writing data to a sql database with pandas - Python</title>
|
|
|
|
<!-- JQuery -->
|
|
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
|
|
<script>
|
|
window.jQuery || document.write('<script src="../theme/js/jquery.min.js"><\/script>')
|
|
</script>
|
|
|
|
<!-- Bootstrap core CSS -->
|
|
<link rel="stylesheet" href="../theme/css/bootstrap.css" />
|
|
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
|
|
<link rel="stylesheet" type="text/css" href="../theme/css/ie10-viewport-bug-workaround.css" />
|
|
<!-- Custom styles for this template -->
|
|
<link rel="stylesheet" type="text/css" href="../theme/css/style.css" />
|
|
<link rel="stylesheet" type="text/css" href="../theme/css/notebooks.css" />
|
|
<link href='https://fonts.googleapis.com/css?family=PT+Serif:400,700|Roboto:400,500,700' rel='stylesheet' type='text/css'>
|
|
|
|
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
|
|
<!--[if lt IE 9]>
|
|
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
|
|
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
|
|
<![endif]-->
|
|
|
|
|
|
<meta name="tags" content="Data Wrangling" />
|
|
|
|
|
|
</head>
|
|
|
|
<body>
|
|
|
|
<div class="navbar navbar-fixed-top">
|
|
<div class="container">
|
|
<div class="navbar-header">
|
|
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
|
|
<span class="icon-bar"></span>
|
|
<span class="icon-bar"></span>
|
|
<span class="icon-bar"></span>
|
|
</button>
|
|
<a class="navbar-brand" href="..">Guillaume Redoulès</a>
|
|
</div>
|
|
<div class="navbar-collapse collapse" id="searchbar">
|
|
|
|
<ul class="nav navbar-nav navbar-right">
|
|
<li class="dropdown">
|
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">About<span class="caret"></span></a>
|
|
<ul class="dropdown-menu">
|
|
<li><a href="../pages/about.html">About Guillaume</a></li>
|
|
<li><a href="https://github.com/redoules">GitHub</a></li>
|
|
<li><a href="https://www.linkedin.com/in/guillaume-redoul%C3%A8s-33923860/">LinkedIn</a></li>
|
|
</ul>
|
|
</li>
|
|
<li class="dropdown">
|
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Data Science<span class="caret"></span></a>
|
|
<ul class="dropdown-menu">
|
|
<li><a href="..#Blog">Blog</a></li>
|
|
<li><a href="..#Python">Python</a></li>
|
|
<li><a href="..#Bash">Bash</a></li>
|
|
<li><a href="..#SQL">SQL</a></li>
|
|
<li><a href="..#Mathematics">Mathematics</a></li>
|
|
<li><a href="..#Machine_Learning">Machine Learning</a></li>
|
|
<li><a href="..#Projects">Projects</a></li>
|
|
</ul>
|
|
</li>
|
|
<li class="dropdown">
|
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Projects<span class="caret"></span></a>
|
|
<ul class="dropdown-menu">
|
|
<li><a href="https://github.com/redoules/redoules.github.io">Notes (Github)</a></li>
|
|
</ul>
|
|
</li>
|
|
|
|
<!--<li class="dropdown">
|
|
<a href="../feeds/blog.rss.xml">Blog RSS</a>
|
|
</li>-->
|
|
|
|
|
|
</ul>
|
|
|
|
<form class="navbar-form" action="../search.html" onsubmit="return validateForm(this.elements['q'].value);">
|
|
<div class="form-group" style="display:inline;">
|
|
<div class="input-group" style="display:table;">
|
|
<span class="input-group-addon" style="width:1%;"><span class="glyphicon glyphicon-search"></span></span>
|
|
<input class="form-control search-query" name="q" id="tipue_search_input" placeholder="e.g. scikit KNN, pandas merge" required autocomplete="off" type="text">
|
|
</div>
|
|
</div>
|
|
</form>
|
|
|
|
</div>
|
|
<!--/.nav-collapse -->
|
|
</div>
|
|
</div>
|
|
|
|
|
|
|
|
<!-- end of header section -->
|
|
<div class="container">
|
|
<!-- <div class="alert alert-warning" role="alert">
|
|
Did you find this page useful? Please do me a quick favor and <a href="#" class="alert-link">endorse me for data science on LinkedIn</a>.
|
|
</div> -->
|
|
<section id="content" class="body">
|
|
<header>
|
|
<h1>
|
|
Writing data to a sql database with pandas
|
|
</h1>
|
|
<ol class="breadcrumb">
|
|
<li>
|
|
<time class="published" datetime="2018-08-03T17:38:00+02:00">
|
|
03 août 2018
|
|
</time>
|
|
</li>
|
|
<li>Python</li>
|
|
<li>Data Wrangling</li>
|
|
</ol>
|
|
</header>
|
|
<div class='article_content'>
|
|
<p>When manipulating you data using pandas, it is sometimes useful to store a dataframe.
|
|
Pandas provides multiple ways to export dataframes. The most common consist in exporting to a csv, a pickle, to hdf or to excel.
|
|
However, exporting to a sql database can prove very useful. Indeed, having a well structured database is a great for storing all the data related to your analysis in one place.</p>
|
|
<p>In this tutorial, we will see how to store a dataframe in a new table of a sqlite dataframe. Note than it would also work with any other sql database a long as you change the connxion to the one that suits your needs.</p>
|
|
<p>First let's import pandas and sqlite3</p>
|
|
<div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">pandas</span> <span class="kn">as</span> <span class="nn">pd</span>
|
|
<span class="kn">import</span> <span class="nn">sqlite3</span>
|
|
<span class="kn">from</span> <span class="nn">sqlite3</span> <span class="kn">import</span> <span class="n">Error</span>
|
|
</pre></div>
|
|
|
|
|
|
<div class="highlight"><pre><span></span><span class="c1"># Example dataframe</span>
|
|
|
|
<span class="n">raw_data</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'fruit'</span><span class="p">:</span> <span class="p">[</span><span class="s1">'Banana'</span><span class="p">,</span> <span class="s1">'Orange'</span><span class="p">,</span> <span class="s1">'Apple'</span><span class="p">,</span> <span class="s1">'lemon'</span><span class="p">,</span> <span class="s2">"lime"</span><span class="p">,</span> <span class="s2">"plum"</span><span class="p">],</span>
|
|
<span class="s1">'color'</span><span class="p">:</span> <span class="p">[</span><span class="s1">'yellow'</span><span class="p">,</span> <span class="s1">'orange'</span><span class="p">,</span> <span class="s1">'red'</span><span class="p">,</span> <span class="s1">'yellow'</span><span class="p">,</span> <span class="s2">"green"</span><span class="p">,</span> <span class="s2">"purple"</span><span class="p">],</span>
|
|
<span class="s1">'kcal'</span><span class="p">:</span> <span class="p">[</span><span class="mi">89</span><span class="p">,</span> <span class="mi">47</span><span class="p">,</span> <span class="mi">52</span><span class="p">,</span> <span class="mi">15</span><span class="p">,</span> <span class="mi">30</span><span class="p">,</span> <span class="mi">28</span><span class="p">]</span>
|
|
<span class="p">}</span>
|
|
|
|
<span class="n">df</span> <span class="o">=</span> <span class="n">pd</span><span class="o">.</span><span class="n">DataFrame</span><span class="p">(</span><span class="n">raw_data</span><span class="p">,</span> <span class="n">columns</span> <span class="o">=</span> <span class="p">[</span><span class="s1">'fruit'</span><span class="p">,</span> <span class="s1">'color'</span><span class="p">,</span> <span class="s1">'kcal'</span><span class="p">])</span>
|
|
<span class="n">df</span>
|
|
</pre></div>
|
|
|
|
|
|
<div>
|
|
<style>
|
|
.dataframe thead tr:only-child th {
|
|
text-align: right;
|
|
}
|
|
|
|
.dataframe thead th {
|
|
text-align: left;
|
|
}
|
|
|
|
.dataframe tbody tr th {
|
|
vertical-align: top;
|
|
}
|
|
</style>
|
|
<table border="1" class="dataframe">
|
|
<thead>
|
|
<tr style="text-align: right;">
|
|
<th></th>
|
|
<th>fruit</th>
|
|
<th>color</th>
|
|
<th>kcal</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
<tr>
|
|
<th>0</th>
|
|
<td>Banana</td>
|
|
<td>yellow</td>
|
|
<td>89</td>
|
|
</tr>
|
|
<tr>
|
|
<th>1</th>
|
|
<td>Orange</td>
|
|
<td>orange</td>
|
|
<td>47</td>
|
|
</tr>
|
|
<tr>
|
|
<th>2</th>
|
|
<td>Apple</td>
|
|
<td>red</td>
|
|
<td>52</td>
|
|
</tr>
|
|
<tr>
|
|
<th>3</th>
|
|
<td>lemon</td>
|
|
<td>yellow</td>
|
|
<td>15</td>
|
|
</tr>
|
|
<tr>
|
|
<th>4</th>
|
|
<td>lime</td>
|
|
<td>green</td>
|
|
<td>30</td>
|
|
</tr>
|
|
<tr>
|
|
<th>5</th>
|
|
<td>plum</td>
|
|
<td>purple</td>
|
|
<td>28</td>
|
|
</tr>
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
|
|
<p>Now that the DataFrame has been created, let's push it to the sqlite database called mydatabase.db in a new table called tutyfrutty</p>
|
|
<div class="highlight"><pre><span></span><span class="n">db_file</span> <span class="o">=</span> <span class="s2">".</span><span class="se">\\</span><span class="s2">mydatabase.db"</span>
|
|
<span class="k">try</span> <span class="p">:</span>
|
|
<span class="k">with</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">db_file</span><span class="p">)</span> <span class="k">as</span> <span class="n">conn</span><span class="p">:</span>
|
|
<span class="n">df</span><span class="o">.</span><span class="n">to_sql</span><span class="p">(</span><span class="s2">"tutyfrutty"</span><span class="p">,</span> <span class="n">conn</span><span class="p">)</span>
|
|
<span class="k">except</span> <span class="n">Error</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
|
|
<span class="k">print</span><span class="p">(</span><span class="n">e</span><span class="p">)</span>
|
|
<span class="k">except</span> <span class="ne">ValueError</span> <span class="p">:</span>
|
|
<span class="k">print</span><span class="p">(</span><span class="s2">"The TABLE tutyfrutty already exists, read below to understand how to handle this case"</span><span class="p">)</span>
|
|
</pre></div>
|
|
|
|
|
|
<p>Note that if the table tutyfrutty was already existing, the to_sql function will return a ValueError. </p>
|
|
<p>This is where, the if_exists option comes into play. Let's look at the docstring of this function : </p>
|
|
<div class="highlight"><pre><span></span><span class="sd">"""</span>
|
|
<span class="sd">if_exists : {'fail', 'replace', 'append'}, default 'fail'</span>
|
|
<span class="sd"> - fail: If table exists, do nothing.</span>
|
|
<span class="sd"> - replace: If table exists, drop it, recreate it, and insert data.</span>
|
|
<span class="sd"> - append: If table exists, insert data. Create if does not exist.</span>
|
|
<span class="sd">"""</span>
|
|
</pre></div>
|
|
|
|
|
|
<p>Let's say, I want to update my dataframe with some new rows </p>
|
|
<div class="highlight"><pre><span></span><span class="n">df</span><span class="o">.</span><span class="n">loc</span><span class="p">[</span><span class="nb">len</span><span class="p">(</span><span class="n">df</span><span class="p">)</span><span class="o">+</span><span class="mi">1</span><span class="p">]</span> <span class="o">=</span> <span class="p">[</span><span class="s1">'Cranberry'</span><span class="p">,</span> <span class="s1">'red'</span><span class="p">,</span> <span class="mi">308</span><span class="p">]</span>
|
|
<span class="n">df</span>
|
|
</pre></div>
|
|
|
|
|
|
<div>
|
|
<style>
|
|
.dataframe thead tr:only-child th {
|
|
text-align: right;
|
|
}
|
|
|
|
.dataframe thead th {
|
|
text-align: left;
|
|
}
|
|
|
|
.dataframe tbody tr th {
|
|
vertical-align: top;
|
|
}
|
|
</style>
|
|
<table border="1" class="dataframe">
|
|
<thead>
|
|
<tr style="text-align: right;">
|
|
<th></th>
|
|
<th>fruit</th>
|
|
<th>color</th>
|
|
<th>kcal</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
<tr>
|
|
<th>0</th>
|
|
<td>Banana</td>
|
|
<td>yellow</td>
|
|
<td>89</td>
|
|
</tr>
|
|
<tr>
|
|
<th>1</th>
|
|
<td>Orange</td>
|
|
<td>orange</td>
|
|
<td>47</td>
|
|
</tr>
|
|
<tr>
|
|
<th>2</th>
|
|
<td>Apple</td>
|
|
<td>red</td>
|
|
<td>52</td>
|
|
</tr>
|
|
<tr>
|
|
<th>3</th>
|
|
<td>lemon</td>
|
|
<td>yellow</td>
|
|
<td>15</td>
|
|
</tr>
|
|
<tr>
|
|
<th>4</th>
|
|
<td>lime</td>
|
|
<td>green</td>
|
|
<td>30</td>
|
|
</tr>
|
|
<tr>
|
|
<th>5</th>
|
|
<td>plum</td>
|
|
<td>purple</td>
|
|
<td>28</td>
|
|
</tr>
|
|
<tr>
|
|
<th>7</th>
|
|
<td>Cranberry</td>
|
|
<td>red</td>
|
|
<td>308</td>
|
|
</tr>
|
|
<tr>
|
|
<th>8</th>
|
|
<td>Cranberry</td>
|
|
<td>red</td>
|
|
<td>308</td>
|
|
</tr>
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
|
|
<p>I can now replace the table with the new values using the "replace" option</p>
|
|
<div class="highlight"><pre><span></span><span class="n">db_file</span> <span class="o">=</span> <span class="s2">".</span><span class="se">\\</span><span class="s2">mydatabase.db"</span>
|
|
<span class="k">try</span> <span class="p">:</span>
|
|
<span class="k">with</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">db_file</span><span class="p">)</span> <span class="k">as</span> <span class="n">conn</span><span class="p">:</span>
|
|
<span class="n">df</span><span class="o">.</span><span class="n">to_sql</span><span class="p">(</span><span class="s2">"tutyfrutty"</span><span class="p">,</span> <span class="n">conn</span><span class="p">,</span> <span class="n">if_exists</span><span class="o">=</span><span class="s2">"replace"</span><span class="p">)</span>
|
|
<span class="k">except</span> <span class="n">Error</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
|
|
<span class="k">print</span><span class="p">(</span><span class="n">e</span><span class="p">)</span>
|
|
</pre></div>
|
|
</div>
|
|
<aside>
|
|
<div class="bug-reporting__panel">
|
|
<h3>Find an error or bug? Have a suggestion?</h3>
|
|
<p>Everything on this site is avaliable on GitHub. Head on over and <a href='https://github.com/redoules/redoules.github.io/issues/new'>submit an issue.</a> You can also message me directly by <a href='mailto:guillaume.redoules@gadz.org'>email</a>.</p>
|
|
</div>
|
|
</aside>
|
|
</section>
|
|
|
|
</div>
|
|
<!-- start of footer section -->
|
|
<footer class="footer">
|
|
<div class="container">
|
|
<p class="text-muted">
|
|
<center>This project contains 105 pages and is available on <a href="https://github.com/redoules/redoules.github.io">GitHub</a>.
|
|
<br/>
|
|
Copyright © Guillaume Redoulès,
|
|
<time datetime="2018">2018</time>.
|
|
</center>
|
|
</p>
|
|
</div>
|
|
</footer>
|
|
|
|
<!-- This jQuery line finds any span that contains code highlighting classes and then selects the parent <pre> tag and adds a border. This is done as a workaround to visually distinguish the code inputs and outputs -->
|
|
<script>
|
|
$( ".hll, .n, .c, .err, .k, .o, .cm, .cp, .c1, .cs, .gd, .ge, .gr, .gh, .gi, .go, .gp, .gs, .gu, .gt, .kc, .kd, .kn, .kp, .kr, .kt, .m, .s, .na, .nb, .nc, .no, .nd, .ni, .ne, .nf, .nl, .nn, .nt, .nv, .ow, .w, .mf, .mh, .mi, .mo, .sb, .sc, .sd, .s2, .se, .sh, .si, .sx, .sr, .s1, .ss, .bp, .vc, .vg, .vi, .il" ).parent( "pre" ).css( "border", "1px solid #DEDEDE" );
|
|
</script>
|
|
|
|
|
|
<!-- Load Google Analytics -->
|
|
<script>
|
|
/*
|
|
(function(i, s, o, g, r, a, m) {
|
|
i['GoogleAnalyticsObject'] = r;
|
|
i[r] = i[r] || function() {
|
|
(i[r].q = i[r].q || []).push(arguments)
|
|
}, i[r].l = 1 * new Date();
|
|
a = s.createElement(o),
|
|
m = s.getElementsByTagName(o)[0];
|
|
a.async = 1;
|
|
a.src = g;
|
|
m.parentNode.insertBefore(a, m)
|
|
})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
|
|
|
|
ga('create', 'UA-66582-32', 'auto');
|
|
ga('send', 'pageview');
|
|
*/
|
|
</script>
|
|
<!-- End of Google Analytics -->
|
|
|
|
<!-- Bootstrap core JavaScript
|
|
================================================== -->
|
|
<!-- Placed at the end of the document so the pages load faster -->
|
|
<script src="../theme/js/bootstrap.min.js"></script>
|
|
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
|
|
<script src="../theme/js/ie10-viewport-bug-workaround.js"></script>
|
|
|
|
|
|
</body>
|
|
|
|
</html> |