<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Robin Linderborg on Medium]]></title>
        <description><![CDATA[Stories by Robin Linderborg on Medium]]></description>
        <link>https://medium.com/@robinlinderborg?source=rss-c3bf1677019------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*z1QWUWSd0gkwTL32OL0obg.jpeg</url>
            <title>Stories by Robin Linderborg on Medium</title>
            <link>https://medium.com/@robinlinderborg?source=rss-c3bf1677019------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 21:17:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@robinlinderborg/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A visual introduction to the dot product]]></title>
            <link>https://medium.com/@robinlinderborg/a-visual-introduction-to-the-dot-product-3e7b65240c09?source=rss-c3bf1677019------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e7b65240c09</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[linear-algebra]]></category>
            <dc:creator><![CDATA[Robin Linderborg]]></dc:creator>
            <pubDate>Mon, 02 Jul 2018 21:42:43 GMT</pubDate>
            <atom:updated>2018-07-02T22:05:24.389Z</atom:updated>
            <content:encoded><![CDATA[<p>They say the best way to learn is to teach, so here goes my attempt at explaining some basics regarding vectors and the dot product.</p><p>By <em>vector, </em>we mean simply a list of numbers. For example, <em>v = [1, 3]. </em>This particular vector <em>a </em>consists of two numbers but a vector can hold any number of well… numbers.</p><p>We say that <em>v</em> is<em> </em>a vector in the two dimensional space. This space has the nice property that we can easily graph it on a flat surface. Here’s what <em>v</em> looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*4kxsCOEk77Vi6fB3nEgfXQ.png" /><figcaption>The vector <em>[1, 3] is located 1 unit to the right and 3 units to the top.</em></figcaption></figure><p>Let’s add another vector <em>u = [2, 2] </em>to the mix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*VjANL7zKM0Iw8O5R29zsLg.png" /></figure><p>Just as with normal numbers, we can perform common algebraic operations on our two vectors. Adding and subtracting vectors simply means to add and subtract their individual components which produces a new vector of the same shape as the original ones.</p><p>So given <em>v=[3,1]</em> and <em>u=[2,2]</em>, we subtract in the following way: <em>v-u=[3–2,1–2]=[1,-1]</em>. Equivalently, adding the vectors yields the new vector <em>[5,3]</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*p1bS08s8jAJhYmuBeTaamQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*_Yt-9_PyumqRY_mXDaVbwA.png" /><figcaption>Subtracting the vector u from the vector v (left) and adding them together (right).</figcaption></figure><p>Notice how subtracting one vector from another produces a vector that connects the two original vectors if the resulting vector is drawn from the end point of one of them. This is perhaps easier to illustrate with another graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*LYd-Nb9gatmXWR_0jV_5lg.png" /><figcaption>Plotting v-u in a new location.</figcaption></figure><p>That’s all well and good, but how about multiplying them together? Well, as it turns out, there are actually several ways of multiplying vectors. You can multiply the components much like we added and subtracted them above. But we will examine a far more interesting operation here. One that doesn’t produce a vector at all, namely, the <em>dot product</em>.</p><p>Calculating the dot product of two vectors actually involves two operations: multiplication and addition. We start by multiplying the vectors’ components element-wise, i.e. <em>[1,3]*[2,2]=[2,6]</em>. We then add the components of the resulting vector together to produce a single number, i.e. <em>2+6=8</em>. Voila!</p><p>So the dot product of <em>v</em> and <em>u</em> is 8. Great! But why would we want to do this? The dot product, in all its simplicity, actually reveals quite a lot of useful information about the relationship between the two vectors being multiplied.</p><h3>Getting the length of a vector</h3><p>The dot product can be used to determine the length (also called size or magnitude) of a vector. The length of vector <em>v</em> is denoted by <em>|v|</em>. And we can use the dot product to get our answer.</p><p>Remember the Pythagorean theorem which helps us solve for the length of the hypotenuse in a right triangle if we know the lengths of the other sides.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*yLx-Ml13OAYjPwD95dSuyQ.png" /><figcaption>The Pythagorean theorem.</figcaption></figure><p>Now, we can actually use this theorem to determine the length of our original vector <em>v=[1,3]. </em>Since <em>v</em> consists of 1 step in the x direction, and 3 steps in the y direction, we can make a right triangle of its components and just plug in the values in the formula. Just imagine <em>v</em> taking the place of <em>c</em> in the graph above, <em>b</em> being 1 and <em>a</em> being 3. So,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*8gal1v4UhILA_g3TyfqyXQ.png" /></figure><p>which means that the length of <em>v</em> is √10.</p><p>Here’s the cool thing: What we did just now was equivalent to taking the dot product of <em>v</em> with itself. We multiplied the components of <em>v</em> with themselves and added them up, which is just what 3² + 1² means. So the length of vector <em>v</em> is simply the square root of the dot product between <em>v</em> and <em>v</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*Y2Pl3mV8y9L12XX33A8YgQ.png" /></figure><h3>Determining angle</h3><p>You may not be convinced of the usefulness of the dot product quite yet. Here’s another interesting relationship for you. If two vectors are perpendicular (which in two dimensional space means they form a 90-degree angle but generalises to any <em>n</em> dimensional space) their dot product will always be 0. Let’s dig a little deeper and see why that is.</p><p>The Pythagorean theorem is actually just a special case of a more general rule called the <strong>law of cosines. </strong>The latter applies to any triangle whereas the former only works with right triangles. It involves a third term that takes the angle between <em>a</em> and <em>b</em> into account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*UVN5A23MwTxm5M7NRd1SVg.png" /></figure><p>Here, cos<em>θ</em> refers to the cosine of the angle between <em>a</em> and <em>b</em>. Remember that the cosine of an angle is 1 when the angle is 90 degrees. Since the angle <em>θ </em>is always 90° in right triangles (that is the very definition of a right triangle) the whole third term in our equation evaluates to 0 and we are left with the Pythagorean theorem.</p><p>Let’s translate the law of cosines into vector notation. We begin by plotting what we’re working with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*w6yF7o0X-jsuWkYTYM-Wpg.png" /></figure><p>So in vector notation, the law of cosines translates to the following (it might look a bit more complicated but just remember that the <em>|x|</em> notation refers to the length of the vectors, similar to the sides of a triangle).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*oJTg7bgQWtYHMEct4VMUMA.png" /></figure><p>From this version of the law of cosines, we can derive a simpler equation.</p><h4>Step 1</h4><p>Multiply out the left hand side of the equation. And keep in mind that a vector dotted with itself is the length of the vector to the power of 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*7oBek8979jzwbqUYeNYJLw.png" /></figure><h4>Step 2</h4><p>Cancel terms from the left hand side and the right hand side of the equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*bIcC3zXS54LiMR3bO5SGhA.png" /></figure><p>So it turns out that the dot product of two vectors equals the product of their respective lengths times the cosine of the angle formed between them. And if the angle is 90 degrees, the cosine is 0, so the whole expression evaluates to 0.</p><p>Quite nifty!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e7b65240c09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vad vi lärde oss på Openvis Conf Paris]]></title>
            <link>https://medium.com/datastory-se/vad-vi-l%C3%A4rde-oss-p%C3%A5-openvis-conf-paris-d1fdf53bf8fb?source=rss-c3bf1677019------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1fdf53bf8fb</guid>
            <category><![CDATA[data-journalism]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[Robin Linderborg]]></dc:creator>
            <pubDate>Wed, 23 May 2018 11:39:39 GMT</pubDate>
            <atom:updated>2018-05-23T11:39:39.787Z</atom:updated>
            <content:encoded><![CDATA[<p>Förra veckan reste delar av Datastory-teamet — Daniel, Arek, Jialing och undertecknad —till årets upplaga av Openvis Conf, en konferens om datavisualisering som för första gången lämnade USA och hölls i Paris.</p><p>Schemat var fullspäckat med föreläsningar av designers, datajournalister och programmerare i världsklass. Här är några spaningar vi gjorde och länkar som vi på tog med oss från Frankrike.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KeFoVfvB8w0_OHa1hxLuog.jpeg" /><figcaption>Ett urval av fotografierna i Moritz Stefaners konstprojekt Multiplicity. Grafik: Moritz Stefaner.</figcaption></figure><h3><strong>Daniel Lapidus</strong></h3><p>Sisi Wei (från ProPublica) talade om “Open Design” under parollen <em>Let others redesign your work</em> — hur gör en organisation för att låta användare remixa och omdesigna upplevelser och produkter på egen hand för att passa deras tycke och smak.</p><p>Detta fick mig att tänka på hur vi på Datastory kan erbjuda bättre verktyg för medskapare. Kan vi skapa verktyg som är flexibla och bjuder in till att medskapa design? Kan vi som komplement till att diskutera nya “features” med våra användare <strong>erbjuda en mer direkt miljö att omstöpa och förbättra verktyg?</strong></p><p>Det var också kul att återupptäcka Open Street Map under “The Planet is the Dataset”. <a href="https://www.openstreetmap.org/"><strong>Open Street Map</strong></a><strong> lever i skymundan av Google Maps men har ett fantastiskt rikt dataset med otroliga möjligheter att extrahera stora mängder data. </strong>Tjänsten underhålls numera av över 1 miljon volontärer. <br>Erik Escoffier berättade under seminariet hur enkelt det är att t.ex. analysera gatunamn eller ta reda på hur många frisörer, butiker eller skolor som finns inom en viss region. Med några enkla geografiska databasfrågor samlade han snabbt ihop 1000-tals rader med data för vidare analys.</p><h3><strong>Arek Mytych</strong></h3><p>Dagen före konferensen besökte vi utställningen <a href="https://123data.paris/">123 Data</a>. Det var väldigt inspirerande att se hur datavisualisering kan se ut utan begränsningarna som webbformatet för med sig. Ett av projekten på utställningen var Moritz Stefaners Multiplicity, som han också berättade om under sin keynote på konferensen. Projektet utgick från en stor mängd instagrambilder som han använde för att skapa en visuell bild av Paris som kunde navigeras med hjälp av en joystick. (Mer om detta i Robins reflektioner nedan.)</p><p>Några andra saker jag tar med mig från konferensen är:</p><p>Federica Fragapane visade med sitt <a href="http://www.storiesbehindaline.com/">projekt om immigration</a> till Italien hur mycket information och erfarenheter som kan rymmas i även kvantitativt små dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vVT3xVrYVb2DZEXZafs-Vg.png" /><figcaption>Federica Fragapane använde ett minimalistiskt uttryck för att visualisera migrationsvägar till Italien.</figcaption></figure><p>Steven Franconeris föreläsning om långsamt vs snabbt tänkande var väldigt bra och tydliggjorde hur dessa två begrepp kan hjälpa en att skapa bättre dataviusaliseringar. Han har sammanfattat <a href="https://twitter.com/SteveFranconeri/status/996309494929018880">huvudpoängerna i den här Twittertråden</a>.</p><p>Vissa sessioner var lite för tekniska för min smak. Å andra sidan blev det en bra balans på det stora hela. Maskininlärning är stort just nu, och så även Augmented Reality (AR). Om jag var en spelare skulle jag satsa pengar på att dessa två teknologier kommer att bli väldigt betydelsefulla i framtiden.</p><h3><strong>Jialing Li</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/209/1*7n5hnBW2aUW05zCp_VKDnA.png" /><figcaption>Jialings porträtt av Lynn Cherny, OpenvisConfs konferencier.</figcaption></figure><p>Som designer föredrar jag att skriva och rita för att samla mina första intryck. Olika karaktärer, djur och grafer kan förmedla en mer intuitiv uppfattning av innehållet för mig och publiken och ger ett effektivt sätt att guida läsaren genom materialet.</p><p>Här följer några av mina anteckningar från konferensen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uOIdR9latOpU2_DOtO9akg.png" /><figcaption>Miriah Meyers föreläsning <em>Designing Effective Visualizations.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i8N5PTE3VVx7mAXB5mjJQQ.jpeg" /><figcaption>Thinking with Data Visualizations Fast and Slow med Steven Franconeri.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*dQanjZ8WOBMI4UX_-l032g.png" /><figcaption>Min reaktion på föreläsningen om Bayesiansk statistik och osäkerhetsanalys 😅</figcaption></figure><h3><strong>Robin Linderborg</strong></h3><p>Att artificiell intelligens (AI) och maskininlärning (ML) är på frammarsch har nog inte gått någon förbi vid det här laget. Datorer kan nu slå människor i spel som schack och Go, ringa och <a href="https://ai.googleblog.com/2018/05/duplex-ai-system-for-natural-conversation.html">boka restaurangbord</a>, och <a href="https://newatlas.com/boston-dynamics-atlas-running/54573/">jaga människor genom skogar</a> (äntligen?).</p><p>Dessa teknologiska framsteg är både fantastiska och skrämmande, och får med rätta stor uppmärksamhet. Men nästan lika intressant är det som sker i kölvattnet av spetsforskningen. När “vanliga människor” kan lära sig och applicera tekniker från en domän och applicera dem inom sitt eget område. Vi fick se flera exempel på detta under konferensen och jag är övertygad om att det här bara är början.</p><p>Moritz Stefaners projekt <a href="https://truth-and-beauty.net/projects/multiplicity">Multiplicity</a> utgår från en samling med tiotusentals fotografier av Paris. För att skapa reda i detta gigantiska material använder han först <a href="https://en.wikipedia.org/wiki/Computer_vision">datorseende</a> för att konvertera bilderna till ett format som en statistisk modell kan förstå. Därefter instruerar han modellen att gruppera bilderna efter typ av innehåll.</p><p>Fotografier av blommor hamnar i en låda, fotografier av människor bredvid Eiffeltornet i en annan. I slutändan bildar fotografierna inte bara ett vackert rutnät, utan tydliggör även trender av vad människor intresserar sig för (och kanske även hur pass förutsägbara vi är).</p><p>Ian Johnson från Google använde en liknande teknik i sin föreläsning <em>Machine Learning for Visualization</em>. I Googles lekfulla applikation <a href="https://quickdraw.withgoogle.com/">Quick, Draw!</a> får användaren ett ord (t.ex. katt) och ska snabbt rita objektet på skärmen. I dag har hundratusentals människor från hela världen testat spelet, och alla ritningar finns sparade i ett öppet dataset. Genom att gruppera bilderna efter ursprungsland och motiv kunde han hitta intressanta mönster som hade varit svårfångade, om inte omöjliga att hitta, med manuellt arbete. För den som vill leka med datasetet själv finns alla <a href="https://quickdraw.withgoogle.com/data">bilder att ladda ner här</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*RZZOPMnCyIErC6L7q9ksbg.png" /><figcaption>Jialing Li ritade av ritningarna i Quick, Draw!</figcaption></figure><h3>Ytterligare länkar</h3><p><a href="https://public.flourish.studio/visualisation/46915/">En visualisering av alla tweets från konferensen</a>.</p><p>Både Moritz Stefaner och Ian Johnson använde en teknik från maskininlärdning som kallas t-SNE som du kan <a href="https://distill.pub/2016/misread-tsne/">läsa mer om och utforska här</a>.</p><p>Hela programmet till OpenVis Conf finns här: <a href="http://www.openvisconf.com/#speakers">http://www.openvisconf.com/#speakers</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1fdf53bf8fb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datastory-se/vad-vi-l%C3%A4rde-oss-p%C3%A5-openvis-conf-paris-d1fdf53bf8fb">Vad vi lärde oss på Openvis Conf Paris</a> was originally published in <a href="https://medium.com/datastory-se">Datastory</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reshaping Data in Python]]></title>
            <link>https://medium.com/hackernoon/reshaping-data-in-python-fa27dda2ff77?source=rss-c3bf1677019------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa27dda2ff77</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Robin Linderborg]]></dc:creator>
            <pubDate>Fri, 20 Jan 2017 14:29:38 GMT</pubDate>
            <atom:updated>2017-07-14T22:00:55.986Z</atom:updated>
            <content:encoded><![CDATA[<p>I really enjoyed Jean-Nicholas Hould’s article on <a href="http://www.jeannicholashould.com/tidy-data-in-python.html">Tidy Data in Python</a>, which in turn is based on <a href="http://vita.had.co.nz/papers/tidy-data.pdf">this paper on Tidy Data</a> by Hadley Wickham. In a sense, the conclusions presented are intuitive and obvious when you think about them. But data analysis can be abstract. Finding the right vocabulary for what you’re doing isn’t always easy.</p><p>In this post, I want to focus exclusively on the process of reshaping data, i.e. converting or transforming data from one format to another. There will be some repetition from Hould’s article, but the goal is to outline the various data formats that we frequently encounter, name them and name the operations we use to transform the data.</p><h3><strong>The long format</strong></h3><p>Let’s begin with looking at a table where the data is tidy. We will be referring to this as <em>long </em>format data (although other naming conventions exist, see below). Borrowing Wickham’s definition, in this format a) each variable forms a column, b) each observation forms a row, and c) each type of observational unit forms a table.</p><p>An example of long format data is this made-up table of three individual’s cash balance on certain dates.</p><pre>In  : df<br>Out :<br>  <strong>   date        person   dollars</strong><br><strong>0</strong>    2000-01-03  Michael  200<br><strong>1</strong>    2000-01-03  George   500<br><strong>2</strong>    2000-01-03  Lisa     450<br><strong>3</strong>    2000-01-04  Michael  180.5<br><strong>4</strong>    2000-01-04  George   450<br><strong>5</strong>    2000-01-04  Lisa     448<br><strong>6</strong>    2000-01-05  Michael  177<br><strong>7</strong>    2000-01-05  George   420<br><strong>8</strong>    2000-01-05  Lisa     447<br><strong>9</strong>    2000-01-06  Michael  150<br><strong>10</strong>   2000-01-06  George   300<br><strong>11</strong>   2000-01-06  Lisa     344.6</pre><p>The format of this table can be referred to as the:</p><ul><li><em>stacked format</em>, because the individual observations are stacked on top of each other.</li><li><em>record format</em>, because each row is a single record, i.e. a single observation.</li><li><em>long format</em>, because this format will be long in the vertical direction as opposed to wide in the horizontal direction.</li></ul><h3>Pivoting data</h3><p>If this table is already tidy, why would we want to reshape it to another format? Well, we might be interested in visually comparing the balance of the individuals by date. Or we might be interested in plotting the data as a time series, where each horizontal line represents one individual.</p><p>In pandas, we can accomplish just that by using the <em>pivot</em> method of the dataframe. This produces a “pivot table”, which will be familiar to Excel users.</p><pre>In  : df.pivot(index=&#39;date&#39;, columns=&#39;name&#39;, values=&#39;dollars&#39;)<br>Out :<br><strong>name        George  Lisa   Michael</strong><br><strong>date</strong><br><strong>2000-01-03</strong>  500.0   450.0  200.0<br><strong>2000-01-04</strong>  450.0   448.0  180.5<br><strong>2000-01-05</strong>  420.0   447.0  177.0<br><strong>2000-01-06</strong>  300.0   344.6  150.0</pre><p>Whatever column you specify as the <em>columns</em> argument will be used to create new columns (each unique entry will form a new column). The column you specify as the <em>values</em> argument will form the values of those columns, and the index will be made up of… you guessed it, the column you specify as the <em>index</em> argument.</p><p>The format of this table can be referred to as:</p><ul><li><em>wide format</em>, because the table is now wider rather than longer.</li><li><em>unstacked format</em>, because the individual observations (one person/one date) are no longer stacked on top of each other.</li></ul><p>A bit confusingly, pandas dataframes also come with a <em>pivot_table</em> method, which is a generalization of the <em>pivot</em> method. Whenever you have duplicate values for one index/column pair, you need to use the <em>pivot_table</em>. Let’s look at one example.</p><p>Let’s say we have data of the number of cookies that George, Lisa, and Michael have sold. Each row in our table represents one sale occasion, which means that there could be multiple rows with the same seller for a given date.</p><pre>In  : df_cookies<br>Out :<br>   <strong>cookies_sold  date        name</strong><br><strong>0</strong>  1             2000–01–01  George<br><strong>1</strong>  3             2000–01–01  Michael<br><strong>2</strong>  3             2000–01–01  Lisa<br><strong>3</strong>  2             2000–01–01  George<br><strong>4</strong>  4             2000–01–01  Lisa</pre><p>If we try to <em>pivot</em> this dataframe, we get a ValueError.</p><pre>In  : df_cookies.pivot(index=&#39;date&#39;,<br>                       columns=&#39;name&#39;,<br>                       values=&#39;cookies_sold&#39;)<br>Out :<br>...<br>ValueError: Index contains duplicate entries, cannot reshape</pre><p>Unlike our previous balance dataframe, the values in the cookies dataframe must be aggregated in order to be pivoted since George and Lisa sold cookies on multiple occasions in one single day. In other words, when we ask pandas to pivot our data, it can’t find a single value to return for duplicate pairs of dates/names. Pandas can, however, give us the sum, or the mean, or any other aggregated value for each date/name pair.</p><pre>In  : df_cookies.pivot_table(index=&#39;date&#39;,<br>                             columns=&#39;name&#39;,<br>                             values=&#39;cookies_sold&#39;)<br>Out :<br><strong>name        George  Lisa  Michael</strong><br><strong>date</strong><br><strong>2000-01-01</strong>  1.5     3.5   3.0</pre><p>The default aggregation function that pandas uses is the mean, but we can easily change that using the <em>aggfunc</em> argument.</p><pre>In  : df_cookies.pivot_table(index=&#39;date&#39;,<br>                             columns=&#39;name&#39;,<br>                             values=&#39;cookies_sold&#39;<br>                             aggfunc=&#39;sum&#39;)<br>Out :<br><strong>name        George  Lisa  Michael</strong><br><strong>date</strong><br><strong>2000-01-01</strong>  3       7     3</pre><h3>Stacking and unstacking data</h3><p>In addition to the pivoting methods, pandas also has the two related concepts of stacking and unstacking data. These are primarily designed to operate on multi-indexed dataframes.</p><p>Let’s create a multi-indexed dataframe of our original balance dataframe.</p><pre>In  : df_multi = df.set_index([&#39;date&#39;, &#39;name&#39;])<br>In  : df_multi<br>Out :<br>                     <strong>dollars</strong><br><strong>date        name</strong><br><strong>2000–01–03  Michael</strong>  200.0<br>          <strong>  George</strong>   500.0<br>          <strong>  Lisa</strong>     450.0<br><strong>2000–01–04  Michael</strong>  180.5<br>          <strong>  George</strong>   450.0<br>          <strong>  Lisa</strong>     448.0<br><strong>2000–01–05  Michael</strong>  177.0<br>          <strong>  George</strong>   420.0<br>           <strong> Lisa</strong>     447.0<br><strong>2000–01–06  Michael</strong>  150.0<br>           <strong> George</strong>   300.0<br>           <strong> Lisa</strong>     344.6</pre><p>Remember, this is stacked data. Each row corresponds to one row. With <em>DataFrame.stack</em> and <em>DataFrame.unstack</em>, we can toggle between hierarchical indices and hierarchical columns. In this case, we have a hierarchical index, so let’s see what <em>unstack</em> does.</p><pre>In  : df_multi.unstack()<br>Out :<br>            <strong>dollars</strong><br><strong>name</strong>        <strong>George  Lisa   Michael</strong><br><strong>date</strong>   <br><strong>2000-01-03</strong>  500.0   450.0  200.0<br><strong>2000-01-04</strong>  450.0   448.0  180.5<br><strong>2000-01-05</strong>  420.0   447.0  177.0<br><strong>2000-01-06</strong>  300.0   344.6  150.0</pre><p>As you can see, the operation moved one level of our hierarchical index to form a new level of columns in the dataframe. To move back to a stacked format, we simple use <em>stack</em>.</p><pre>In  : df_multi.unstack().stack()<br>Out :<br>                     <strong>dollars</strong><br><strong>date        name</strong><br><strong>2000–01–03  Michael</strong>  200.0<br>          <strong>  George</strong>   500.0<br>          <strong>  Lisa</strong>     450.0<br><strong>2000–01–04  Michael</strong>  180.5<br>          <strong>  George</strong>   450.0<br>           <strong> Lisa</strong>     448.0<br><strong>2000–01–05  Michael</strong>  177.0<br>           <strong> George</strong>   420.0<br>           <strong> Lisa</strong>     447.0<br><strong>2000–01–06  Michael</strong>  150.0<br>           <strong> George</strong>   300.0<br>           <strong> Lisa</strong>     344.6</pre><h3>Transposing data</h3><p>Pandas has an easy way of rotating dataframes, i.e. switching the locations of columns and indices. Simply use the <em>T</em> attribute to rotate the data.</p><pre>In  : df = pd.DataFrame({&#39;a&#39;: [1, 2], <br>                         &#39;b&#39;: [3, 4]}, index=[‘one’, ‘two’])<br>In  : df<br>Out :<br>    <strong>a</strong> <strong>b</strong><br><strong>one</strong> 1 3<br><strong>two</strong> 2 4</pre><pre>In  : df.T<br>Out :<br>  <strong>one two</strong><br><strong>a</strong> 1   2<br><strong>b</strong> 3   4</pre><h3>Unpivoting data with melt</h3><p>Discovering pandas’ <em>melt</em> function was a game-changer for me. It basically allows you to unpivot data however you want. In other words, we use <em>melt</em> to transform wide data to long data.</p><p>Say we have a wide format dataframe like this one.</p><pre><strong>  country 2010  2011  2012</strong><br><strong>0</strong> Canada  55    55    86<br><strong>1</strong> Iraq    56    32    22<br><strong>2</strong> Italy   3     56    11</pre><p>To reshape this data to a long format, where each row represents one country/year pair, we use <em>melt </em>(which is not a dataframe method, but a top-level import from pandas).</p><pre>In  : pd.melt(df, id_vars=&#39;country&#39;, value_vars=[2010, 2011, 2012])<br>Out :<br><strong>   country  year  value</strong><br><strong>0</strong>  Canada   2010  55<br><strong>1</strong>  Iraq     2010  56<br><strong>2</strong>  Italy    2010  3<br><strong>3</strong>  Canada   2011  55<br><strong>4</strong>  Iraq     2011  32<br><strong>5</strong>  Italy    2011  56<br><strong>6</strong>  Canada   2012  86<br><strong>7</strong>  Iraq     2012  22<br><strong>8</strong>  Italy    2012  11</pre><p>Hopefully this overview makes the pandas tools for reshaping data a bit clearer. Happy data wrangling!</p><blockquote><a href="http://bit.ly/Hackernoon">Hacker Noon</a> is how hackers start their afternoons. We’re a part of the <a href="http://bit.ly/atAMIatAMI">@AMI</a>family. We are now <a href="http://bit.ly/hackernoonsubmission">accepting submissions</a> and happy to <a href="/service/mailto:partners@amipublications.com">discuss advertising &amp;sponsorship</a> opportunities.</blockquote><blockquote>To learn more, <a href="https://goo.gl/4ofytp">read our about page</a>, <a href="http://bit.ly/HackernoonFB">like/message us on Facebook</a>, or simply, <a href="https://goo.gl/k7XYbx">tweet/DM @HackerNoon.</a></blockquote><blockquote>If you enjoyed this story, we recommend reading our <a href="http://bit.ly/hackernoonlatestt">latest tech stories</a> and <a href="https://hackernoon.com/trending">trending tech stories</a>. Until next time, don’t take the realities of the world for granted!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa27dda2ff77" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/reshaping-data-in-python-fa27dda2ff77">Reshaping Data in Python</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>