<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Luis Bruemmer, Author at Be on the Right Side of Change</title>
	<atom:link href="https://blog.finxter.com/author/luisbruemmer/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.finxter.com/author/luisbruemmer/</link>
	<description></description>
	<lastBuildDate>Tue, 08 Mar 2022 15:16:26 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://blog.finxter.com/wp-content/uploads/2020/08/cropped-cropped-finxter_nobackground-32x32.png</url>
	<title>Luis Bruemmer, Author at Be on the Right Side of Change</title>
	<link>https://blog.finxter.com/author/luisbruemmer/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>JavaScript Primitive Data Types</title>
		<link>https://blog.finxter.com/javascript-data-types/</link>
		
		<dc:creator><![CDATA[Luis Bruemmer]]></dc:creator>
		<pubDate>Fri, 04 Mar 2022 20:05:15 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Web Development]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=222514</guid>

					<description><![CDATA[<p>In this tutorial, we will learn everything about JavaScript DataTypes. We will get to know the different kinds of data types, how to determine data types, and how to convert them into other data types. In short, JavaScript has seven primitive data types, namely: String, Number, BigInt, Boolean, undefined, null, and Symbol. Besides that, there ... <a title="JavaScript Primitive Data Types" class="read-more" href="https://blog.finxter.com/javascript-data-types/" aria-label="Read more about JavaScript Primitive Data Types">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/javascript-data-types/">JavaScript Primitive Data Types</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="JavaScript Primitive Data Types" width="937" height="527" src="https://www.youtube.com/embed/g_tWdi40Txs?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>In this tutorial, we will learn everything about JavaScript DataTypes. We will get to know the different kinds of data types, how to determine data types, and how to convert them into other data types.</p>



<p>In short, JavaScript has seven <strong>primitive data types</strong>, namely: <code>String</code>, <code>Number</code>, <code>BigInt</code>, <code>Boolean</code>, <code>undefined</code>, <code>null</code>, and <code>Symbol</code>. </p>



<p>Besides that, there are <strong>JavaScript objects</strong>, but they will be part of another JavaScript tutorial. This tutorial will focus on primitive data types exclusively. </p>



<p>We determine the data type of a variable with the <code>typeof</code> operator. </p>



<p>And since JavaScript is a dynamically typed language, we do not have to specify the data type of a newly created variable. </p>



<p>Also, data types are automatically converted when we reassign a variable to a new value of a different data type. &nbsp;</p>



<p>Great documentation about JavaScript data types can be found <a rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures" target="_blank">here</a>.</p>



<hr class="wp-block-separator"/>



<p>This is part of our <strong><em>Learn JavaScript</em></strong> series:</p>



<ol class="wp-block-list"><li><a rel="noreferrer noopener" href="https://blog.finxter.com/javascript-intro-how-to-see-your-code-output/" data-type="post" data-id="175068" target="_blank">JavaScript Intro &#8211; How to See Your Code Output?</a></li><li><a rel="noreferrer noopener" href="Syntax, Statements, Variables, and Comments" data-type="URL" data-id="JavaScript: Syntax, Statements, Variables, and Comments" target="_blank">JavaScript Syntax, Statements, Variables, and Comments</a></li><li><a rel="noreferrer noopener" href="https://blog.finxter.com/javascript-assignment-and-arithmetic-operators/" data-type="post" data-id="211383" target="_blank">JavaScript Assignment and Arithmetic Operators</a></li><li><a href="https://blog.finxter.com/javascript-data-types/" data-type="post" data-id="222514" target="_blank" rel="noreferrer noopener"><strong>JavaScript Data Types</strong></a></li></ol>



<h2 class="wp-block-heading">Primitive Data Types</h2>



<p>Primitive data types are types that are already built into the programming language. They are the most basic form of data type, and they are very different from each other. JavaScript treats variables differently depending on the data type these variables have.</p>



<p>There are seven primitive data types which we will now discuss one after the other.</p>



<h3 class="wp-block-heading">String</h3>



<p>A string is just a series of characters used to represent some form of text.</p>



<p>Let&#8217;s have a look at an example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">let word1 = "Hello!";</pre>



<p>We create the variable <code>word1</code> using the keyword <code>let</code>. We assign this variable the value <code>"Hello!"</code> which is a string. We put the content of the text inside double-quotes. </p>



<p>Alternatively, we can use single quotes as well:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">let word2 = 'House';</pre>



<p>Whether we use double quotes or single quotes is a matter of taste. However, when we have apostrophes in our text, it&#8217;s necessary to use double quotes:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">let sentence = "It's nice to meet you!";</pre>



<p>because this would not work:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">let sentence = 'It's nice to meet you!';</pre>



<p>The computer thinks that the string ends after <code>"It"</code> and does not know what to do with the rest of the line of code.</p>



<p>Thus, if we create our string with double quotes, we cannot use double quotes within the string, and if we create our string with single quotes, we cannot use single quotes within the string.</p>



<h3 class="wp-block-heading">Number</h3>



<p>The Number data type is one of two numeric data types that JavaScript provides us with.</p>



<p>A number can be an integer or a decimal:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">let x = 5;
let y = 2.1;</pre>



<p>Here, we declare two variables <code>x</code> and <code>y</code>. Variable <code>x</code> is assigned the integer value <code>5</code> and <code>y</code> is assigned the decimal value <code>2.1</code>.</p>



<p>With numbers, we can perform arithmetic operations, like addition, subtraction, multiplication, division, etc.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">let z = x + y;
console.log(z);
>>> 7.1</pre>



<p>We declare the variable <code>z</code> and assign it the sum of <code>x</code> and <code>y</code>. When we output <code>z</code> with <code>console.log()</code>, we can see that the sum of <code>x</code> and <code>y</code> is <code>7.1</code>.</p>



<h3 class="wp-block-heading">BigInt</h3>



<p>The other numeric data type is <code>BigInt</code> which can represent integer values of arbitrary length. The <code>Number</code> data type, however, has limitations.</p>



<p>We create <code>BigInt</code> numbers by adding the letter <code>n</code> to the end of an integer value:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">let a = 43158490244031231567560143649357809134n;
console.log(a);
>>> 43158490244031231567560143649357809134n</pre>



<p>We create this huge integer number and add the letter <code>n</code> as a suffix. When we output the value of the variable that we assigned this value, the <a href="https://blog.finxter.com/javascript-intro-how-to-see-your-code-output/" data-type="post" data-id="175068" target="_blank" rel="noreferrer noopener">output</a> shows the exact same number.</p>



<p>When we do the same without an <code>n</code>, this is what we get:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">let b = 43158490244031231567560143649357809134;
console.log(b);
>>> 4.315849024403123e+37</pre>



<p>This way, the output is much less precise than before.</p>



<h3 class="wp-block-heading">Boolean</h3>



<p>A Boolean can have two values: <code>true</code> or <code>false</code>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">let booleanValue1 = true;
let booleanValue2 = false;</pre>



<p>The first variable has the value <code>true</code> and the second one has the value <code>false</code>. We can use boolean expressions in <code>if</code> statements or in loops.</p>



<p>For example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">if (booleanValue2) {
    console.log("Hey guys!");
}
>>> 
</pre>



<p>As we can see, this code snippet does not produce any output. </p>



<p>The <code>if</code> statement checks if the statement inside the parenthesis is <code>true</code> or <code>false</code>. Since <code>booleanValue2</code> is set to <code>false</code>, the <code>console.log()</code> statement is not executed.</p>



<p>Let&#8217;s have a look at another example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">if (booleanValue1) {
    console.log("Hey guys!");
}
>>> Hey guys!</pre>



<p>The only thing we changed here was we replaced <code>booleanValue2</code> with <code>booleanValue1</code>. Since <code>booleanValue1</code> is <code>true</code>, the <code>console.log()</code> statement will be executed and we get an output.</p>



<h2 class="wp-block-heading">Undefined</h2>



<p>When we declare a variable and we do not assign it a value, the value of this variable is undefined:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">let d;
console.log(d);
>>> undefined
</pre>



<p>When we assign this variable for example a numeric value it is not undefined anymore:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">d = 4;
console.log(d);
>>> 4</pre>



<p>However, we can set the variable back to undefined:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">d = undefined;
console.log(d);
>>> undefined</pre>



<h3 class="wp-block-heading">Null</h3>



<p>The <code>null</code> value in <a href="https://blog.finxter.com/javascript-developer-income-and-opportunity/" data-type="post" data-id="191233" target="_blank" rel="noreferrer noopener">JavaScript</a> represents a value that is nonexistent.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">let n = null;
console.log(n);
>>> null</pre>



<p>One might think that <code>null</code> is the same as <code>undefined</code>. </p>



<p>But there are differences between these two. We must explicitly set a variable to <code>null</code> to make it <code>null</code>, whereas a variable is automatically set to <code>undefined</code> when we do not assign it a value.</p>



<p>So, null values are nonexistent and undefined values are not yet existent.</p>



<h3 class="wp-block-heading">Symbol</h3>



<p>Symbols can be used as unique values. They are created with the <code>Symbol()</code> function:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">let symbol1 = Symbol("Symbol");
let symbol2 = Symbol("Symbol");</pre>



<p>Here, we create two symbols: <code>symbol1</code> and <code>symbol2</code>. Both symbols contain the same description (<code>"Symbol"</code>).</p>



<p>Let&#8217;s check if they are unique. We achieve that with the strict equality operator <code>===</code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">console.log(symbol1 === symbol2);
>>> false
</pre>



<p>When we compare the symbols with the strict equality operator, we get the result <code>false</code>. That shows us that these two symbols are unique.</p>



<p>This is where <code>Symbols</code> differ from strings because if we do the same with strings, this happens:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">let string1 = "Hi!";
let string2 = "Hi!";
console.log(string1 === string2);
>>> true
</pre>



<p>We create two identical strings. When we compare them with the strict equality operator, the result is <code>true</code> since these strings are actually identical.</p>



<h2 class="wp-block-heading">Determine Data Type with typeof Operator</h2>



<p>We use the <code>typeof</code> operator to determine the data type of a variable. This is useful when we don&#8217;t know what data type a certain variable has.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">let x1 = 5;
console.log(typeof (x1));
>>> number</pre>



<p>We assign the newly declared variable <code>x1</code> the number <code>5</code>. </p>



<p>Then we check the type of <code>x1</code> with the <code>typeof</code> operator and put it inside a <code>console.log()</code> statement to output the type.</p>



<p>The output says that the type of <code>x1</code> is <code>number</code>.</p>



<h2 class="wp-block-heading">Data Type Conversion</h2>



<p>Since JavaScript is a dynamic language, we do not have to specify the type of a variable when declaring it:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">let v = 3;
console.log(typeof(v));
>>> number
</pre>



<p>We declare the variable <code>v</code> and assign it the value <code>3</code>. When we output the type of this variable, we can see that the type of <code>v</code> is <code>number</code> although we never specified that.</p>



<p>Due to these dynamic features, we can reassign the variable <code>v</code> a value of another type easily:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">v = "Hello";
console.log(typeof(v));
>>> string
</pre>



<p>We assign the variable the string <code>"Hello"</code>. And when we output the type of <code>v</code> now, we can see that we successfully changed the type to <code>string</code>.</p>



<h2 class="wp-block-heading">Summary</h2>



<p>All in all, we learned about the different data types that JavaScript provides us with. We learned the data type&#8217;s characteristics, how to determine the data type of a variable, and how to reassign variables to values of another data type.</p>



<p>If you wish to learn more about JavaScript, stay tuned for the other tutorials that are being released to Finxter.</p>



<p>And for more tutorials about other computer and data science-related topics, check out the <a href="https://blog.finxter.com/email-academy/" data-type="page" data-id="12278">Finxter email academy</a>!</p>



<p>Happy Coding!</p>



<p></p>
<p>The post <a href="https://blog.finxter.com/javascript-data-types/">JavaScript Primitive Data Types</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>JavaScript Assignment and Arithmetic Operators</title>
		<link>https://blog.finxter.com/javascript-assignment-and-arithmetic-operators/</link>
		
		<dc:creator><![CDATA[Luis Bruemmer]]></dc:creator>
		<pubDate>Sat, 26 Feb 2022 16:50:28 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=211383</guid>

					<description><![CDATA[<p>In this JavaScript tutorial, we will learn all about the assignment and arithmetic operators that we can use when programming with JavaScript. In short, with the arithmetic operators, we can perform arithmetic operations like addition, subtraction, multiplication, division, remainder, and exponentiation. We use the assignment operators to assign values to variables. Great documentations about JavaScript ... <a title="JavaScript Assignment and Arithmetic Operators" class="read-more" href="https://blog.finxter.com/javascript-assignment-and-arithmetic-operators/" aria-label="Read more about JavaScript Assignment and Arithmetic Operators">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/javascript-assignment-and-arithmetic-operators/">JavaScript Assignment and Arithmetic Operators</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="JavaScript Assignment and Arithmetic Operators" width="937" height="527" src="https://www.youtube.com/embed/D3XwZLjbWdQ?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>In this JavaScript tutorial, we will learn all about the assignment and arithmetic operators that we can use when programming with JavaScript.</p>



<p>In short, with the arithmetic operators, we can perform arithmetic operations like addition, subtraction, multiplication, division, remainder, and exponentiation.</p>



<p>We use the assignment operators to assign values to variables.</p>



<p>Great documentations about JavaScript operators can be found <a rel="noreferrer noopener" href="https://www.w3schools.com/jsref/jsref_operators.asp" target="_blank">here</a> and <a rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators" target="_blank">here</a>.</p>



<hr class="wp-block-separator"/>



<p>This is part of our <strong><em>Learn JavaScript</em></strong> series:</p>



<ol class="wp-block-list"><li><a rel="noreferrer noopener" href="https://blog.finxter.com/javascript-intro-how-to-see-your-code-output/" data-type="post" data-id="175068" target="_blank">JavaScript Intro &#8211; How to See Your Code Output?</a></li><li><a rel="noreferrer noopener" href="Syntax, Statements, Variables, and Comments" data-type="URL" data-id="JavaScript: Syntax, Statements, Variables, and Comments" target="_blank">JavaScript Syntax, Statements, Variables, and Comments</a></li><li><a rel="noreferrer noopener" href="https://blog.finxter.com/javascript-assignment-and-arithmetic-operators/" data-type="post" data-id="211383" target="_blank"><strong>JavaScript Assignment and Arithmetic Operators</strong></a></li></ol>



<h2 class="wp-block-heading">Arithmetic Operators</h2>



<p>We will start with the arithmetic operators. As stated in the introduction, these operators are used to perform arithmetic operations.</p>



<p>We create two initial variables and give each a numerical value:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">let x = 2;
let y = 7;</pre>



<p>So, <code>x</code> has the value 2 and <code>y</code> has the value 7. We will work with these values throughout this section.</p>



<p>We also create the variable <code>z</code> which is supposed to hold the resulting values:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">let z;</pre>



<p>We only need to declare the variables once with the keyword <code>let</code>. For the following examples, we can just reassign them to other values.</p>



<p>Now, we can perform the actual operations. We start with addition:</p>



<h3 class="wp-block-heading">Addition Operator</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">z = x + y;</pre>



<p>We assign the variable <code>z</code> the addition of <code>x</code> and <code>y</code>. <code>x</code> and <code>y</code> are the operands and <code>+</code> is the operator.</p>



<p>We will now output <code>z</code> to see what value it has:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">console.log(z);
// 9</pre>



<p>As we can see, we successfully added <code>x</code> and <code>y</code> since 2+7 is indeed 9.</p>



<p>Likewise, we can perform the other arithmetic operations like</p>



<h3 class="wp-block-heading">Subtraction Operator</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">z = y - x;
console.log(z);
// 5</pre>



<h3 class="wp-block-heading">Multiplication Operator</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">z = y * x;
console.log(z);
// 14</pre>



<h3 class="wp-block-heading">Division Operator</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">z = y / x;
console.log(z);
// 3.5</pre>



<p>So, the difference between these statements is the arithmetic operator. In addition, we use <code>+</code>, in subtraction, we use <code>-</code>, in multiplication, we use <code>*</code>, and in division, we use <code>/</code>.</p>



<p>There are two remaining arithmetic operators: exponentiation and remainder.</p>



<h3 class="wp-block-heading">Exponentiation Operator</h3>



<p>The exponentiation operator raises the first operand to the power of the second one:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">z = y ** x;
console.log(z);
// 49</pre>



<p>So, we calculate 7<sup>2</sup> which is 49.</p>



<h3 class="wp-block-heading">Remainder Operator</h3>



<p>The last operator, the remainder operator, returns this value:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">z = y % x;
console.log(z);
// 1</pre>



<p>This operator is used to calculate the remaining value after a division.</p>



<p>The example says the following: <code>7 / 2 = 3</code> and the remainder is 1. So, the 2 fits into the 7 three whole times and there is 1 remaining. The remainder operation only outputs the remainder itself.</p>



<p>Maybe you have come across the remainder operator under its other term &#8220;<a href="https://blog.finxter.com/python-modulo/" data-type="post" data-id="104">modu</a><a href="https://blog.finxter.com/python-modulo/" data-type="post" data-id="104" target="_blank" rel="noreferrer noopener">l</a><a href="https://blog.finxter.com/python-modulo/" data-type="post" data-id="104">o</a>&#8220;.  </p>



<h2 class="wp-block-heading">Increment and Decrement</h2>



<p>For incrementing and decrementing, JavaScript provides us with the operators of the same name. But there is a difference between using them as prefixes or postfixes.</p>



<p>Let&#8217;s create a new variable <code>x</code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">let x = 5;</pre>



<p>Now, we perform a postfix incrementation of <code>x</code> and assign this value to a newly created variable <code>y</code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">let y = x++;</pre>



<p>Let&#8217;s see what value <code>y</code> has:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">console.log(y);
// 5</pre>



<p><code>x</code> has the following value:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">console.log(x);
// 6</pre>



<p>So, with the postfix incrementation, <code>y</code> was not affected, but <code>x</code> was incremented by one.</p>



<p>Let&#8217;s do the same again, but this time with prefix incrementation:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">x = 5;
y = ++x;</pre>



<p>We set <code>x</code> back to 5 and we perform a prefix incrementation of <code>x</code> and assign this value to <code>y</code>.</p>



<p><code>y</code> now has this value:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">console.log(y);
// 6</pre>



<p>And <code>x</code> has this value:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">console.log(x);
// 6</pre>



<p>As we can see, <code>y</code> was also affected by the incrementation because with prefix incrementation the values for both <code>x</code> and <code>y</code> were incremented by 1.</p>



<h3 class="wp-block-heading">Postfix Decrementation Operator</h3>



<p>The same applies to decrementing. We start with postfix decrementation:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">x = 5;
y = x--;</pre>



<p>We set <code>x</code> back to 5 and we perform a postfix decrementation that we assign to <code>y</code>.</p>



<p><code>y</code> has this value:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">console.log(y);
// 5</pre>



<p>And <code>x</code> has this value:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">console.log(x);
// 4</pre>



<p>So, <code>y</code> was not affected.</p>



<h3 class="wp-block-heading">Prefix Decrementation Operator</h3>



<p>Whereas, with the prefix decrementation, it looks like this:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">x = 5;
y = --x;</pre>



<p><code>x</code> is again set back to 5 and we perform a prefix decrementation that we set to <code>y</code>.</p>



<p><code>y</code> has this value:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">console.log(y);
// 4</pre>



<p>And <code>x</code> has this value:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">console.log(x);
// 4</pre>



<p>Thus, <code>y</code> is also affected by the prefix decrementation as was the case with prefix incrementation.</p>



<h2 class="wp-block-heading">Assignment operators</h2>



<p>We use assignment operators to assign values to variables.</p>



<h3 class="wp-block-heading">Simple Assignment Operator</h3>



<p>The equal sign <code>=</code> is known as the <strong>assignment operator</strong>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">let a = 4;</pre>



<p>Here, we create the variable <code>a</code>, and we assign it the numeric value 4.</p>



<h3 class="wp-block-heading">Addition Assignment Operator</h3>



<p>We can also use the assignment operator to add a value to a variable:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">a += 1;</pre>



<p>Here, we assign the variable <code>a</code> the new value which is the initial value plus 1. Let&#8217;s check what value <code>a</code> now has:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">console.log(a);
// 5</pre>



<p><code>a</code> has the value 5 because it was initially 4 and we added 1 to it.</p>



<p>The statement</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">a += 1;</pre>



<p>is the same as</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">a = a + 1;</pre>



<p>because we set the variable equal to the initial variable&#8217;s value and add 1.</p>



<h3 class="wp-block-heading">Subtraction Assignment Operator</h3>



<p>With subtraction, it looks like similar:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">a = 4;
a -= 1;
console.log(a);
// 3
</pre>



<p>First, we set <code>a</code> back to 4. Then we subtract 1 from <code>a</code> and assign the new value to <code>a</code>. Then we output the value of <code>a</code> which is 3. And as with addition, the statement</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">a -= 1;</pre>



<p>is the same as</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">a = a - 1;</pre>



<h3 class="wp-block-heading">Multiplication Assignment Operator</h3>



<p>Multiplication looks like this:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">a = 4;
a *= 2;
console.log(a);
// 8
</pre>



<p>Again, we set <code>a</code> back to the value 4. Then, we multiply <code>a</code> by 2 and add the new value to <code>a</code>. Next, we output the new value of <code>a</code> and we can see that it is now 8.</p>



<h3 class="wp-block-heading">Division Assignment Operator</h3>



<p>Division also works like this:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">a = 4;
a /= 2;
console.log(a);
// 2</pre>



<p>After setting a back to 4, we divide it by 2 and assign the new value to <code>a</code>. The output shows that we did this successfully as we get 2 as the output which is the result of dividing 4 by 2.</p>



<h3 class="wp-block-heading">Remainder Assignment Operator</h3>



<p>We do the same with the remainder:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">a = 4;
a %= 2;
console.log(a);
// 0</pre>



<p>We set a back to 4 and then we calculate the remainder of dividing 4 by 2 and set this value to <code>a</code>.</p>



<p>Since 2 fits into 4 two times and there is no remaining value, <code>a</code> has the value 0 which is confirmed by outputting a.</p>



<h3 class="wp-block-heading">Exponentiation Assignment Operator</h3>



<p>The exponentiation assignment works the same way:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">a = 4;
a **= 3;
console.log(a);
// 64</pre>



<p><code>a</code> is set back to 4. Afterward, we calculate 4 to the power of 3 and assign the new value to the variable <code>a</code>. The output is 64 because 4<sup>3</sup> equals 64.</p>



<p>The remaining assignment operators are a bit different from the ones we have seen by now.</p>



<h3 class="wp-block-heading">Left-Shift Assignment Operator</h3>



<p>We will start with the left shift assignment:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">a = 5;
a &lt;&lt;= 2;
console.log(a);
// 20</pre>



<p>So, what is happening here? We set the variable <code>a</code> that we already declared to the value 5. Then we perform the left shift. In this case, we move the bits 2 to the left and assign the new value to our variable <code>a</code>.</p>



<p>The 2-bit representation of the number 5 is 00101 because 1*2<sup>2</sup> + 1*2<sup>0</sup> = 5.</p>



<p>And we shift these bits 2 to the left, so now we have got this 2-bit number: 10100 which is 1*2<sup>4</sup> + 1*2<sup>2</sup> = 20.</p>



<h3 class="wp-block-heading">Right-Shift Assignment Operator</h3>



<p>Similarly, we can perform a right shift assignment:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">a = 9;
a >>= 2;
console.log(a);
// 2</pre>



<p>We set <code>a</code> to 9. Then, we perform the right shift assignment where we shift the bits 2 to the right. The 2-bit representation of 9 is: 01001.</p>



<p>When we shift the bits 2 to the right, we get 00010 which is 2. The other 1 is outside the scope and is therefore not taken into account.</p>



<p>The remaining assignment operators are bitwise assignment operators.</p>



<h3 class="wp-block-heading">Bitwise AND Assignment Operator</h3>



<p>The first one is the<strong> bitwise AND</strong> assignment operator:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">a = 5;
a &amp;= 2;
console.log(a);
// 0</pre>



<p><code>a</code> is set to 5. Then we perform a bitwise and operation of 5 and 2 and the result is then set as the new value for <code>a</code>. The output value of <code>a</code> is 0.</p>



<p>The 2-bit representation of 5 is 00101 and the 2-bit representation of 2 is 00010. When we put these 2-bit numbers above each other and perform a bitwise and operation, we get 00000 which is 0.</p>



<h3 class="wp-block-heading">Bitwise OR Assignment Operator</h3>



<p>Likewise, we do the same for the <strong>bitwise OR</strong> assignment operation.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">a = 5;
a |= 4;
console.log(a);
// 5</pre>



<p>We set <code>a</code> back to 5 again and then we perform a bitwise or operation of 5 and 4 and the result is assigned to <code>a</code>. The result is 5.</p>



<p>The 2-bit representation of 5 is 00101 and the 2-bit representation of 4 is 00100. When we put these 2-bit numbers above each other and perform a bitwise OR operation, we get 00101 which is 5.</p>



<h3 class="wp-block-heading">Bitwise XOR Assignment Operator</h3>



<p>There is also a <strong>bitwise XOR</strong> assignment operation:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">a = 5;
a ^= 4;
console.log(a);
// 1</pre>



<p><code>a</code> is set back to 5 again. Then we perform the bitwise XOR operation of 5 and 4 and we assign the result to <code>a</code>.</p>



<p>The result of a bitwise xor operation of 5 and 4 is binary 00001 which is decimal 1.</p>



<h2 class="wp-block-heading">Summary</h2>



<p>In this tutorial, we learned all about JavaScript&#8217;s assignment and arithmetic operators. We learned how to perform different kinds of arithmetic operations, and how to assign values in different ways.</p>



<p>If you wish to learn more about JavaScript, stay tuned for the other tutorials that are being released to Finxter.</p>



<p>And for more tutorials about other computer and data science-related topics, check out the <a href="https://blog.finxter.com/email-academy/" data-type="page" data-id="12278" target="_blank" rel="noreferrer noopener">Finxter email academy</a>!</p>



<p>Happy Coding!</p>



<p>The post <a href="https://blog.finxter.com/javascript-assignment-and-arithmetic-operators/">JavaScript Assignment and Arithmetic Operators</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>JavaScript: Syntax, Statements, Variables, and Comments</title>
		<link>https://blog.finxter.com/javascript-syntax-statements-variables-and-comments/</link>
		
		<dc:creator><![CDATA[Luis Bruemmer]]></dc:creator>
		<pubDate>Sun, 13 Feb 2022 12:15:34 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Web Development]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=187810</guid>

					<description><![CDATA[<p>In this JavaScript tutorial, we will learn about the language&#8217;s syntax and statements, how to declare variables, and how to create comments. In short, statements are separated by semicolons (";"), but they do not have to when the statements are in separate lines. Variables are mostly declared with either the keyword &#8220;const&#8221; or &#8220;let&#8220;. Regarding ... <a title="JavaScript: Syntax, Statements, Variables, and Comments" class="read-more" href="https://blog.finxter.com/javascript-syntax-statements-variables-and-comments/" aria-label="Read more about JavaScript: Syntax, Statements, Variables, and Comments">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/javascript-syntax-statements-variables-and-comments/">JavaScript: Syntax, Statements, Variables, and Comments</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="JavaScript: Syntax, Statements, Variables, and Comments" width="937" height="527" src="https://www.youtube.com/embed/dW2MHmR4X50?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>In this JavaScript tutorial, we will learn about the language&#8217;s syntax and statements, how to declare variables, and how to create comments.</p>



<ul class="wp-block-list"><li>In short, <strong>statements</strong> are separated by semicolons (<code>";"</code>), but they do not have to when the statements are in separate lines. </li><li><strong>Variables</strong> are mostly declared with either the keyword &#8220;<code>const</code>&#8221; or &#8220;<code>let</code>&#8220;. </li><li>Regarding <strong>comments</strong>, there are two ways to produce comments: one-line comments (<code>"//"</code>) and multi-line comments &#8220;(<code>/* * */</code>&#8220;).</li></ul>



<p>A great reference to read more about these topics can be found <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types" target="_blank" rel="noreferrer noopener">here</a>.</p>



<h2 class="wp-block-heading" id="syntax-and-statements">Syntax and statements</h2>



<p>The syntax of a programming language is a set of rules that describe how a program should be structured. We have got a sequence of instructions that we can execute. </p>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> In JavaScript, these instructions are called <strong><em>statements</em></strong>.</p>



<p>Let&#8217;s have a look at an example statement:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">let x = 42;</pre>



<p>Here, we declare the variable &#8220;<code>x</code>&#8221; with the keyword &#8220;<code>let</code>&#8221; and assign it the value &#8220;<code>42</code>&#8220;. </p>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2753.png" alt="❓" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Note</strong>: If you do not understand what &#8220;<code>let</code>&#8220;, &#8220;<code>x</code>&#8220;, and &#8220;<code>42</code>&#8221; mean here, don&#8217;t worry. We will look at variables in more detail in the next section.</p>



<p>The important thing here is the semicolon (&#8220;<code>;</code>&#8220;) at the end of the code line. </p>



<p>A <strong>semicolon</strong> determines the <strong>end of a statement</strong>. </p>



<p>However, if there is only one statement written in one code line, we do not necessarily have to set the semicolon:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">let x = 42</pre>



<p>That being said, if we put multiple statements into one line of code, the statements have to be separated by semicolons:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">let x = 42; let y = 0;</pre>



<h2 class="wp-block-heading" id="variables">Variables</h2>



<p>As mentioned in the previous section, we will now shift our focus towards <strong>variables</strong>.</p>



<p>A <strong><em>variable</em></strong> is used to <strong><em>store data</em></strong>. </p>



<p>The name of a variable can be freely chosen but it has to start with a letter, an underscore, or a dollar sign. </p>



<p>Since JavaScript is case-sensitive, a variable called &#8220;<code>jeff</code>&#8221; is not the same as &#8220;<code>Jeff</code>&#8221; because the second &#8220;<code>Jeff</code>&#8221; starts with a capital letter and the other one does not.</p>



<p>In JavaScript there are four ways to declare variables: </p>



<ul class="wp-block-list"><li>with the keywords &#8220;<code>var</code>&#8220;, </li><li>&#8220;<code>let</code>&#8220;, </li><li>&#8220;<code>const</code>&#8220;, or </li><li>with no keyword at all.</li></ul>



<p>When we declare a variable with no keyword, it looks like this:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">a = 10;</pre>



<p>The name of the variable here is &#8220;<code>a</code>&#8221; and we assign it the number &#8220;<code>10</code>&#8221; using the assignment operator &#8220;<code>=</code>&#8220;. However, using no keyword at all can lead to errors and should be avoided.</p>



<p>That&#8217;s why we should always use a keyword for the variable declaration.</p>



<p>One keyword is &#8220;<code>var</code>&#8220;:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">var b = "Hello";</pre>



<p>The &#8220;<code>var</code>&#8221; keyword is the original way to declare a variable in JavaScript. Using this keyword, we create function-scoped variables. Here, we declare a variable called &#8220;<code>b</code>&#8221; and assign it the string <code>"Hello"</code>.</p>



<p>We can check the current value for &#8220;<code>b</code>&#8221; by outputting the value of the variable:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">console.log(b);</pre>



<p><strong>Result</strong>: <code>Hello</code></p>



<p>We use the &#8220;<code>console.log()</code>&#8221; statement for producing output. And as we can see, the value of &#8220;<code>b</code>&#8221; is <code>"Hello"</code>.</p>



<p>However, when using &#8220;<code>var</code>&#8221; we can change the value of an existing variable.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">b = 40;</pre>



<p>We reassign the value of &#8220;<code>b</code>&#8221; to the number &#8220;<code>40</code>&#8220;. Let&#8217;s see what the output is now:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">console.log(b);</pre>



<p><strong>Result</strong>:  <code>40</code></p>



<p>We successfully reassigned the variable &#8220;<code>b</code>&#8221; to another value.</p>



<p>Also, when declaring a variable with &#8220;<code>var</code>&#8220;, we do not immediately have to set a value for that variable:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">var c;</pre>



<p>When we output &#8220;<code>c</code>&#8220;, this is what happens:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">console.log(c);</pre>



<p><strong>Output</strong>: <code>undefined</code></p>



<p>We get &#8220;<code>undefined</code>&#8221; as output because the variable does not hold any value yet. But we can, of course, give that variable a value now:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">c = 5;
console.log(c);
// Output: 5</pre>



<p>There are two remaining ways to declare a variable: &#8220;<code>const</code>&#8221; and &#8220;<code>let</code>&#8220;. These keywords were added to JavaScript a couple of years ago and they declare block-scoped variables.</p>



<p>Declaring a variable with &#8220;<code>let</code>&#8221; seems to be the same as declaring with &#8220;<code>var</code>&#8220;:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">let d = true;
console.log(d);
// true</pre>



<p>Here, we initially gave the new variable &#8220;<code>d</code>&#8221; the boolean value &#8220;<code>true</code>&#8220;. And as with &#8220;<code>var</code>&#8220;, we can change this variable&#8217;s value to another value:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">d = false;
console.log(d);
// false
</pre>



<p>We can also declare a variable without an initial value:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">let e;
console.log(e);
// undefined
</pre>



<p>So, we declare a variable that we optionally give a value and that we can change later just as we did with &#8220;<code>var</code>&#8220;.</p>



<p>The remaining keyword &#8220;<code>const</code>&#8221; is used to declare a constant:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const pi = 3.14;
console.log(pi);
// 3.14
</pre>



<p>We declare a variable called &#8220;<code>pi</code>&#8221; and give it the value &#8220;<code>3.14</code>&#8220;. </p>



<p>Compared to &#8220;<code>var</code>&#8221; and &#8220;<code>let</code>&#8221; we are not able to reassign another value to the variable because it is a constant. </p>



<p>In addition to that, we immediately have to give a &#8220;<code>const</code>&#8221; variable a value. We cannot declare it without a value.</p>



<h2 class="wp-block-heading" id="when-to-use-which-variable-declaration">When to use which variable declaration</h2>



<p>We learned different ways to declare variables in JavaScript. So, <strong>when should we use which type of declaration?</strong></p>



<p>A general rule of thumb is to always declare variables with the keyword &#8220;<code>const</code>&#8221; first. And if we think a variable&#8217;s value should be able to change and be reassigned, we declare this variable with &#8220;<code>let</code>&#8220;.</p>



<p><strong>But why not with &#8220;<code>var</code>&#8220;? </strong></p>



<p>&#8220;<code>var</code>&#8221; and &#8220;<code>let</code>&#8221; seem to work the same way. However, the scoping behavior of &#8220;<code>var</code>&#8221; can lead to errors which is why &#8220;<code>let</code>&#8221; and &#8220;<code>const</code>&#8221; were created. Thus, it is not necessary to use &#8220;<code>var</code>&#8221; at all. Any variable declaration can be done with either &#8220;<code>const</code>&#8221; or &#8220;<code>let</code>&#8220;.</p>



<h2 class="wp-block-heading" id="comments">Comments</h2>



<p>We always want to document what our code is doing and why our code is doing what it does. Comments are great for explaining our code and they are mandatory to use in any code project, especially in large ones.</p>



<p>We can insert comments anywhere in our code and that does not change our program in any way. They are just there for making the code easier to understand.</p>



<p>In JavaScript, we have got two types of comments: </p>



<ul class="wp-block-list"><li><strong>one-line comments</strong> and </li><li><strong>multi-line comments</strong>.</li></ul>



<p>One-line comments start with two slashes:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">//This is a one-line comment</pre>



<p>As we stated above, comments can be inserted anywhere in our code:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const pi = 3.14; // declare variable "pi" as constant</pre>



<p>The comment does not change the code in any way.</p>



<p><strong>Multi-line comments</strong>, as the name suggests, extend over several lines. </p>



<p>They can be used to create a comment block where we explain something in more detail. They start like this &#8220;<code>/*</code>&#8221; and end like this &#8220;<code>*/</code>&#8221; and anything that stands between that will be treated as a comment:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/*
The following code will
calculate some values and 
assign these values to 
new variables.
*/
</pre>



<h2 class="wp-block-heading" id="summary">Summary</h2>



<p>All in all, we learned the basics about the programming language JavaScript in this article. We learned about statements, how to declare variables, and how to apply comments to our code.</p>



<p>For more tutorials about other computer and data science-related topics, check out the Finxter email academy!</p>



<p>Happy Coding!</p>



<hr class="wp-block-separator"/>



<p><strong>Related Tutorial: </strong></p>



<ul class="wp-block-list"><li><a href="https://blog.finxter.com/typescript-developer-income-and-opportunity/" data-type="post" data-id="187729" target="_blank" rel="noreferrer noopener">TypeScript Developer &#8212; Income and Opportunity</a></li></ul>
<p>The post <a href="https://blog.finxter.com/javascript-syntax-statements-variables-and-comments/">JavaScript: Syntax, Statements, Variables, and Comments</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>[JavaScript Intro] How to See Your Code Output?</title>
		<link>https://blog.finxter.com/javascript-intro-how-to-see-your-code-output/</link>
		
		<dc:creator><![CDATA[Luis Bruemmer]]></dc:creator>
		<pubDate>Sun, 06 Feb 2022 10:54:11 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Web Development]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=175068</guid>

					<description><![CDATA[<p>In this article, we will get an overview of the programming language JavaScript and we will learn how to see our code output and results when working with JavaScript. In short, the easiest and most convenient way to see our JavaScript output is to use the console.log() method which shows a message in our web ... <a title="[JavaScript Intro] How to See Your Code Output?" class="read-more" href="https://blog.finxter.com/javascript-intro-how-to-see-your-code-output/" aria-label="Read more about [JavaScript Intro] How to See Your Code Output?">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/javascript-intro-how-to-see-your-code-output/">[JavaScript Intro] How to See Your Code Output?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="[JavaScript Intro] How to See Your Code Output?" width="937" height="527" src="https://www.youtube.com/embed/dH-xaihySIU?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>In this article, we will get an overview of the programming language JavaScript and we will learn how to see our code output and results when working with JavaScript.</p>



<p>In short, the easiest and most convenient way to see our JavaScript output is to use the <code>console.log()</code> method which shows a message in our web console:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">console.log('Hello, world!');</pre>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="209" height="123" src="https://blog.finxter.com/wp-content/uploads/2022/02/image-30.png" alt="" class="wp-image-175072"/></figure></div>



<p>A great JavaScript documentation can be found <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript">h</a><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript" target="_blank" rel="noreferrer noopener">e</a><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript">re</a>.</p>



<p>This article is the first part of a JavaScript series here on Finxter. Feel free to check out the other articles after going through this one!</p>



<p>Feel free to skip ahead to the different ways to see your output in JavaScript&#8212;we&#8217;ll start slowly with some introductory material next.</p>



<h2 class="wp-block-heading" id="what-is-javascript">What is JavaScript?</h2>



<p>JavaScript is a programming language that was created in 1995 to make websites interactive and more dynamic. Together with HTML and CSS, it defines one of the three core technologies for the front-end of the web. If you used any kind of website where you interacted with the website in some way, you definitely came across JavaScript, maybe without knowing it.</p>



<p>So, why should you learn JavaScript? According to the <strong>&#8220;Stack Overflow Developer Survey 2021&#8221;</strong> <a rel="noreferrer noopener" href="https://insights.stackoverflow.com/survey/2021#technology-most-popular-technologies" target="_blank">JavaScript continues to be the most commonly used programming language</a>. </p>



<p>Thus, although the language was created almost 30 years ago, it is still very much in demand. </p>



<p>There are countless libraries and frameworks built on top of JavaScript, such as React.js or Vue.js. </p>



<p>Hence, there are plenty of options to dive into after learning the language itself.</p>



<h2 class="wp-block-heading" id="javascript-and-html">JavaScript and HTML</h2>



<p>As we already know, JavaScript is mainly used for web development. So, when we are working on a web project, we have an HTML file that looks something like this:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;!DOCTYPE html>
&lt;html>
  &lt;head>
    &lt;meta charset="utf-8">
    &lt;title>My homepage&lt;/title>
  &lt;/head>

  &lt;body>
    &lt;h1>Hello, there!&lt;/h1>
    &lt;p id="p1">A paragraph.&lt;/p>
    
    &lt;script src="main.js">&lt;/script>
  &lt;/body>
&lt;/html>
</pre>



<p>This is not an HTML tutorial. However, we will briefly go through what&#8217;s happening here.</p>



<p>The HTML file starts with a document type declaration which tells the browser what kind of document to expect. </p>



<p>All the actual information about our website is nested in the <code>&lt;html></code> tag. </p>



<p>The <code>&lt;head></code> tag contains the <code>&lt;meta></code> charset tag which specifies the character encoding. </p>



<p>It also contains the <code>&lt;title></code> tag which is the title of our homepage and can be seen in the browser&#8217;s title bar. </p>



<p>Then comes the <code>&lt;body></code> tag where we find the actual content of our webpage. Here, we can see a header tag <code>&lt;h1></code>, a paragraph tag <code>&lt;p></code> with the ID <code>p1</code>, and the <code>&lt;script></code> tag.</p>



<p>If we applied some form of CSS, we would link it in the &#8220;<code>&lt;head></code>&#8221; tag, but we will not do that here since it would be a bit too much for this tutorial.</p>



<p>The really interesting part of the HTML file for us is the &#8220;<code>&lt;script></code>&#8221; tag because it links to our JavaScript file with the <code>src</code> attribute. As we can see, we set the <code>src</code> attribute equal to <code>"main.js"</code> since this is the name of our JavaScript file. When we link a file this way, it means that the HTML file and the JavaScript file have to be in the same folder:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="198" height="83" src="https://blog.finxter.com/wp-content/uploads/2022/02/image-31.png" alt="" class="wp-image-175077"/></figure></div>



<p>I&#8217;m using the code editor <a href="https://code.visualstudio.com/" target="_blank" rel="noreferrer noopener">Visual Studio Code</a> for development. </p>



<p>Here, I created the folder &#8220;<code>JavaScript</code>&#8221; and created two files: &#8220;<code>index.html</code>&#8221; which contains the content we saw above, and the &#8220;<code>main.js</code>&#8221; file.</p>



<h2 class="wp-block-heading" id="modify-the-html-document-with-javascript">Modify the HTML Document with JavaScript</h2>



<p>In this section, we will see how to change the HTML document using JavaScript. </p>



<p>To be able to see the changes, we will have to open the HTML file in some way. There are different ways to do so: We can open the folder where our HTML file and JavaScript file are stored.</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="142" height="69" src="https://blog.finxter.com/wp-content/uploads/2022/02/image-32.png" alt="" class="wp-image-175078"/></figure></div>



<p>Here, we can just double-click on the &#8220;<code>index.html</code>&#8221; file. On my computer, this opens the Chrome browser by default. However, if you want to use another browser, you can right-click on the &#8220;<code>index.html</code>&#8221; file and open the file with another browser.</p>



<p>Doing it this way, we always have to reload our browser window when we make changes to our files. Thus, this method is not that convenient.</p>



<p>Using the code editor VS code that I already referred to, we can download the extension &#8220;Live Server&#8221;. To do so, we go to the &#8220;<code>Extensions</code>&#8221; symbol on the left-hand side and type in &#8220;<code>Live Server</code>&#8220;.</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="501" height="120" src="https://blog.finxter.com/wp-content/uploads/2022/02/image-33.png" alt="" class="wp-image-175079" srcset="https://blog.finxter.com/wp-content/uploads/2022/02/image-33.png 501w, https://blog.finxter.com/wp-content/uploads/2022/02/image-33-300x72.png 300w" sizes="auto, (max-width: 501px) 100vw, 501px" /></figure></div>



<p>After clicking &#8220;<code>Install</code>&#8221; you might have to restart VS code in order to make the extension work properly. </p>



<p>Once we did that, this symbol should appear on the bottom-right corner:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="88" height="52" src="https://blog.finxter.com/wp-content/uploads/2022/02/image-34.png" alt="" class="wp-image-175080"/></figure></div>



<p>When we click that, it opens the HTML file in our browser. </p>



<p>And now, anytime we make changes to the files and save the changes, the changes appear automatically without refreshing the page manually.</p>



<p>This is what the web page looks like at the moment:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="176" height="97" src="https://blog.finxter.com/wp-content/uploads/2022/02/image-35.png" alt="" class="wp-image-175081"/></figure></div>



<p>Now, we head over to the &#8220;<code>main.js</code>&#8221; file and type in our first line of JavaScript code:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">document.write('JavaScript is awesome!');</pre>



<p>This method writes the String <code>"JavaScript is awesome!"</code> to our HTML document. </p>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Notice that we end the command line with a semicolon to define the end of this statement.</p>



<p>So, when we save the &#8220;<code>main.js</code>&#8221; file and have a look at our browser again, we can see the following web page:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="188" height="123" src="https://blog.finxter.com/wp-content/uploads/2022/02/image-36.png" alt="" class="wp-image-175082"/></figure></div>



<p>Compared to the initial web page, we can see that we added the sentence <code>"JavaScript is awesome!"</code> below the rest of the document&#8217;s content. Thus, we successfully modified our HTML document using JavaScript.</p>



<p>We can also change an existing HTML element. Therefore, we use this method:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">document.getElementById('p1').innerHTML = 'A great paragraph';</pre>



<p>Here we access an HTML element by its ID, namely &#8220;<code>p1</code>&#8221; and change the inner HTML to something new, in this case: <code>"A great paragraph"</code>.</p>



<p>When we save the JavaScript file and have a look at our browser again, we can see that the paragraph indeed has changed from <code>"A paragraph"</code> to <code>"A great paragraph"</code>:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="184" height="118" src="https://blog.finxter.com/wp-content/uploads/2022/02/image-37.png" alt="" class="wp-image-175084"/></figure></div>



<h2 class="wp-block-heading" id="display-output-with-the-console">Display Output with the Console</h2>



<p>By now, we saw how to use JavaScript to modify our HTML files and view the changes in our browser. </p>



<p>However, we will often want to get some JavaScript output without modifying an HTML file. </p>



<p>In fact, we do not always work with any kind of HTML when working with JavaScript. A great way to do that is to use the &#8220;<code>console</code>&#8221; object which gives us access to our browser&#8217;s debugging console.</p>



<p>Let&#8217;s see how that works. We add a line to our &#8220;<code>main.js</code>&#8221; file:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">console.log('I am in the console!');</pre>



<p>We apply the console method &#8220;<code>log</code>&#8221; here which outputs a message to the browser&#8217;s console. </p>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2b50.png" alt="⭐" class="wp-smiley" style="height: 1em; max-height: 1em;" /> The <code>console.log()</code> method is the most commonly used way to produce JavaScript output and it is especially useful for testing and debugging.</p>



<p>When we have a look at our web page again, we can see that nothing has changed:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="173" height="112" src="https://blog.finxter.com/wp-content/uploads/2022/02/image-38.png" alt="" class="wp-image-175085"/></figure></div>



<p>That&#8217;s because we did not modify the HTML file in any way. </p>



<p>But when we press <code>CTRL + SHIFT + J</code> on Windows or <code>CMD + SHIFT + J</code> on Mac, the browser console opens:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="254" height="124" src="https://blog.finxter.com/wp-content/uploads/2022/02/image-39.png" alt="" class="wp-image-175086"/></figure></div>



<p>And there we can see the text <code>"I am in the console!"</code> that we put in the &#8220;<code>console.log()</code>&#8221; statement.  </p>



<p>Inside the console, we can also input JavaScript code:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="208" height="104" src="https://blog.finxter.com/wp-content/uploads/2022/02/image-40.png" alt="" class="wp-image-175088"/></figure></div>



<p>However, especially for larger projects, it is recommended to use a code editor for development. Using the browser console for coding is good for quick testing.</p>



<p>If we do not want to use the browser at all for getting JavaScript output, we can produce the output within VS code directly.</p>



<p>Therefore, we need to install the &#8220;Code Runner&#8221; extension:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="426" height="133" src="https://blog.finxter.com/wp-content/uploads/2022/02/image-41.png" alt="" class="wp-image-175089" srcset="https://blog.finxter.com/wp-content/uploads/2022/02/image-41.png 426w, https://blog.finxter.com/wp-content/uploads/2022/02/image-41-300x94.png 300w" sizes="auto, (max-width: 426px) 100vw, 426px" /></figure></div>



<p>And we need <a href="https://nodejs.org/en/" target="_blank" rel="noreferrer noopener">Node.js</a> to be installed.</p>



<p>Our &#8220;<code>main.js</code>&#8221; file now only contains this one line of code:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">console.log('I am in the console!');</pre>



<p>When the JavaScript file is opened, we press CTRL + ALT + N on Windows or CMD + OPTIONS + N on Mac. This runs the JavaScript code and the output will be shown in the output window at the bottom of VS Code:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="351" height="144" src="https://blog.finxter.com/wp-content/uploads/2022/02/image-42.png" alt="" class="wp-image-175091" srcset="https://blog.finxter.com/wp-content/uploads/2022/02/image-42.png 351w, https://blog.finxter.com/wp-content/uploads/2022/02/image-42-300x123.png 300w" sizes="auto, (max-width: 351px) 100vw, 351px" /></figure></div>



<p>This method for creating output is also great to use when we have got a lot of code, but we only want to run a part of it.</p>



<p>We will now add a new line of code to the &#8220;main.js&#8221; file:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">console.log('I am in the console!');
console.log('Hi console!');</pre>



<p>If we ran the whole code, both messages would be shown. </p>



<p>However, we might only want to show the second line. Therefore, we highlight the second line, and then we hit <code>CTRL + ALT + N</code> on Windows or <code>CMD + OPTIONS + N</code> on Mac.</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="421" height="92" src="https://blog.finxter.com/wp-content/uploads/2022/02/image-43.png" alt="" class="wp-image-175092" srcset="https://blog.finxter.com/wp-content/uploads/2022/02/image-43.png 421w, https://blog.finxter.com/wp-content/uploads/2022/02/image-43-300x66.png 300w" sizes="auto, (max-width: 421px) 100vw, 421px" /></figure></div>



<p>This way, we are able to run only a fraction of our code which is especially useful when we are working on a big project and we want to test a part of our code.</p>



<h2 class="wp-block-heading" id="summary">Summary</h2>



<p>In this tutorial, we learned what JavaScript is, how to modify HTML documents with it, and how to view JavaScript output in the browser and in our code editor.</p>



<p>If you wish to learn more about JavaScript, stay tuned for the other tutorials that are being released to Finxter.</p>



<p>And for more tutorials about other computer and data science-related topics, check out the <a href="https://blog.finxter.com/email-academy/" data-type="page" data-id="12278" target="_blank" rel="noreferrer noopener">Finxter email academy</a>!</p>



<p>Happy Coding!</p>



<hr class="wp-block-separator"/>
<p>The post <a href="https://blog.finxter.com/javascript-intro-how-to-see-your-code-output/">[JavaScript Intro] How to See Your Code Output?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Pandas get_dummies() &#8211; A Simple Guide with Video</title>
		<link>https://blog.finxter.com/pandas-get_dummies-a-simple-guide-with-video/</link>
		
		<dc:creator><![CDATA[Luis Bruemmer]]></dc:creator>
		<pubDate>Sat, 22 Jan 2022 15:07:07 +0000</pubDate>
				<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Pandas Library]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=149923</guid>

					<description><![CDATA[<p>In this tutorial, we will learn all about the Pandas function get_dummies(). This method converts categorical data into dummy or indicator variables. Here are the parameters from the official documentation: Parameter Type Description data array-like, Series, or DataFrame Data of which to get the dummy indicators. prefix str, list of str, or dict of str,default ... <a title="Pandas get_dummies() &#8211; A Simple Guide with Video" class="read-more" href="https://blog.finxter.com/pandas-get_dummies-a-simple-guide-with-video/" aria-label="Read more about Pandas get_dummies() &#8211; A Simple Guide with Video">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/pandas-get_dummies-a-simple-guide-with-video/">Pandas get_dummies() &#8211; A Simple Guide with Video</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Pandas get_dummies() - A Simple Guide" width="937" height="527" src="https://www.youtube.com/embed/HPwM_ii1skE?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>In this tutorial, we will learn all about the <a href="https://blog.finxter.com/pandas-quickstart/" data-type="post" data-id="16511" target="_blank" rel="noreferrer noopener">Pandas</a> function <code>get_dummies()</code>. This method converts categorical data into dummy or indicator variables.</p>



<p>Here are the parameters from the <a href="https://pandas.pydata.org/docs/reference/api/pandas.get_dummies.html" target="_blank" rel="noreferrer noopener">official documentation</a>:</p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td><strong>Parameter</strong></td><td><strong>Type</strong></td><td><strong>Description</strong></td></tr><tr><td><code>data</code></td><td>array-like, Series, or DataFrame</td><td>Data of which to get the dummy indicators.</td></tr><tr><td><code>prefix</code></td><td><code><a href="https://blog.finxter.com/python-str-function/" data-type="post" data-id="23735" target="_blank" rel="noreferrer noopener">str</a></code>, list of <code>str</code>, or <code><a href="https://blog.finxter.com/python-dict/" data-type="post" data-id="19866" target="_blank" rel="noreferrer noopener">dict</a></code> of <code>str</code>,<br>default <code>None</code></td><td>String to append to DataFrame column names. Pass a list with the length equal to the number of columns when calling <code>get_dummies()</code> on a DataFrame. Alternatively, <code>prefix</code> can be a <a href="https://blog.finxter.com/python-dictionary/" data-type="post" data-id="5232" target="_blank" rel="noreferrer noopener">dictionary</a> mapping the column names to the prefixes.</td></tr><tr><td><code>prefix_sep</code></td><td><code>str</code>, default ‘_’</td><td>Separator/delimiter to use if <code>prefix</code> is appended. Or pass a list or dictionary as with the prefix.</td></tr><tr><td><code>dummy_na</code></td><td><code><a href="https://blog.finxter.com/python-bool/" data-type="post" data-id="17841" target="_blank" rel="noreferrer noopener">bool</a></code>, default <code>False</code></td><td>Add a column to indicate the <code>NaN</code> values, if <code>False</code>: <code>NaN</code> values are ignored.</td></tr><tr><td><code>columns</code></td><td>list-like, default <code>None</code></td><td>Column names in the DataFrame to be encoded. If <br>columns is <code>None</code>: all the columns with object or category <code>dtype</code> will be converted.</td></tr><tr><td><code>sparse</code></td><td><code>bool</code>, default <code>False</code></td><td>Whether the dummy-encoded columns should be backed by a <code>SparseArray</code> (<code>True</code>) or by a regular NumPy array (<code>False</code>).</td></tr><tr><td><code>drop_first</code></td><td><code>bool</code>, default <code>False</code></td><td>Whether to get k-1 dummies out of k categorical levels by removing the first level.</td></tr><tr><td><code>dtype</code></td><td>dtype, default <code>np.uint8</code></td><td>Data type for the new columns. Only a single <code>dtype</code> is allowed.</td></tr><tr><td></td><td></td><td></td></tr><tr><td><strong>Returns</strong></td><td><strong>Type</strong></td><td><strong>Description</strong></td></tr><tr><td></td><td>DataFrame</td><td>Dummy-coded data</td></tr></tbody></table></figure>



<h2 class="wp-block-heading">The Basic Functionality of get_dummies()</h2>



<p>We will start with a simple example to get to understand how and where we can apply the <code>get_dummies()</code> method and how exactly it works:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pandas as pd
x = ['a', 'b', 'c', 'a', 'c']
pd.get_dummies(x)
</pre>



<p><strong>Output:</strong></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>a</strong></td><td><strong>b</strong></td><td><strong>c</strong></td></tr><tr><td>0</td><td>1</td><td>0</td><td>0</td></tr><tr><td>1</td><td>0</td><td>1</td><td>0</td></tr><tr><td>2</td><td>0</td><td>0</td><td>1</td></tr><tr><td>3</td><td>1</td><td>0</td><td>0</td></tr><tr><td>4</td><td>0</td><td>0</td><td>1</td></tr></tbody></table></figure>



<p>First, we import the Pandas library to be able to use the method. </p>



<p>Second, we create a simple <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="post" data-id="7332" target="_blank">Python list</a> that contains several characters and we assign this list to the variable &#8220;<code>x</code>&#8220;. </p>



<p>Third, we apply the <code>get_dummies()</code> function and inside the function&#8217;s parenthesis, we put in the list &#8220;<code data-enlighter-language="generic" class="EnlighterJSRAW">x</code>&#8221; as the argument. </p>



<p>The output is a Pandas data frame.</p>



<p>The data frame consists of the columns &#8220;<code>a</code>&#8220;, &#8220;<code>b</code>&#8220;, and &#8220;<code>c</code>&#8221; and the rows &#8220;<code>0</code>&#8220;, &#8220;<code>1</code>&#8220;, &#8220;<code>2</code>&#8220;, &#8220;<code>3</code>&#8220;, and &#8220;<code>4</code>&#8220;. The cell entries are either &#8220;<code>0</code>&#8221; or &#8220;<code>1</code>&#8220;. </p>



<p><strong>So, what exactly is happening here?</strong></p>



<p>The column labels <code>"a"</code>, <code>"b"</code>, and <code>"c"</code> are the unique characters from the list that we applied (<code>['a', 'b', 'c', 'a', 'c']</code>). </p>



<p>The number of rows in the data frame equals the length of the list. There are five rows and five characters. The ones and zeros in the data frame are the actual dummy variables. </p>



<p>When we have a look at the first entry (column: &#8220;<code>a</code>&#8220;, row: &#8220;<code>0</code>&#8220;), we observe that this value is a &#8220;<code>1</code>&#8220;. That means that the first entry of the list is the character <code>"a"</code> because it is in row &#8220;0&#8221; (remember: a computer program starts counting at 0) and in column &#8220;<code>a</code>&#8220;.</p>



<p>Another example is the data frame entry in row &#8220;<code>2</code>&#8221; and column &#8220;<code>c</code>&#8220;: This entry is also &#8220;<code>1</code>&#8221; because in the list there is a <code>"c"</code> in third place.   </p>



<h2 class="wp-block-heading">Handling NaN Values</h2>



<p>In this section, we will find out how the <code>get_dummies()</code> function handles <code>NaN</code> values. </p>



<p>For that reason, we create another Python list. This list contains the same values as the one from the first example, only the last character gets replaced with a <code>NaN</code> value:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np
y = ['a', 'b', 'c', 'a', np.nan]
pd.get_dummies(y)
</pre>



<p><strong>Output:</strong></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>a</strong></td><td><strong>b</strong></td><td><strong>c</strong></td></tr><tr><td>0</td><td>1</td><td>0</td><td>0</td></tr><tr><td>1</td><td>0</td><td>1</td><td>0</td></tr><tr><td>2</td><td>0</td><td>0</td><td>1</td></tr><tr><td>3</td><td>1</td><td>0</td><td>0</td></tr><tr><td>4</td><td>0</td><td>0</td><td>0</td></tr></tbody></table></figure>



<p>The new list is assigned to the variable <code>y</code>. </p>



<p>As we can see, the list contains the unique values <code>"a"</code>, <code>"b"</code>, <code>"c"</code>, and <code>"np.nan"</code>. The latter is a NaN value that we created using the <a href="https://blog.finxter.com/numpy-tutorial/" data-type="post" data-id="1356" target="_blank" rel="noreferrer noopener">Numpy library</a> which is why we had to import that library here. </p>



<p>The <code>get_dummies()</code> function creates a data frame just like in the first example. </p>



<p>Again, we get three columns <code>"a"</code>, <code>"b"</code>, and <code>"c"</code> and five rows. The only difference compared to the first example is the last row. Here, we have zeros exclusively. That&#8217;s because the last value from the list is a <code>NaN</code> value which we can&#8217;t assign to either <code>"a"</code>, <code>"b"</code>, or <code>"c"</code>.</p>



<p>However, we can make the <code>NaN</code> value visible in the resulting data frame by applying the <code>dummy_na</code> parameter:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.get_dummies(y, dummy_na=True)</pre>



<p><strong>Output:</strong></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>a</strong></td><td><strong>b</strong></td><td><strong>c</strong></td><td><strong>NaN</strong></td></tr><tr><td>0</td><td>1</td><td>0</td><td>0</td><td>0</td></tr><tr><td>1</td><td>0</td><td>1</td><td>0</td><td>0</td></tr><tr><td>2</td><td>0</td><td>0</td><td>1</td><td>0</td></tr><tr><td>3</td><td>1</td><td>0</td><td>0</td><td>0</td></tr><tr><td>4</td><td>0</td><td>0</td><td>0</td><td>1</td></tr></tbody></table></figure>



<p>We set this parameter to <code>True</code>. That way, we add another column with the label <code>NaN</code>. </p>



<p>In the resulting data frame, the last row&#8217;s <code>NaN</code> entry is now <code>1</code> because of the <code>NaN</code> value in the list.</p>



<h2 class="wp-block-heading">Apply get_dummies() to a DataFrame</h2>



<p>By now, we have seen how to apply the <code>get_dummies()</code> function on lists. </p>



<p>However, we can also apply this function to DataFrames. So, let&#8217;s create a simple data frame:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">df = pd.DataFrame({'A': ['a', 'b', 'b'], 'B': ['a', 'c', 'b'], 'C': [1,2,3], 'D': [4,5,6]})
print(df)
</pre>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>A</strong></td><td><strong>B</strong></td><td><strong>C</strong></td><td><strong>D</strong></td></tr><tr><td>0</td><td>a</td><td>a</td><td>1</td><td>4</td></tr><tr><td>1</td><td>b</td><td>c</td><td>2</td><td>5</td></tr><tr><td>2</td><td>b</td><td>b</td><td>3</td><td>6</td></tr></tbody></table></figure>



<p>We get four columns <code>"A"</code>, <code>"B"</code>, <code>"C"</code>, and <code>"D"</code> and three rows <code>"0"</code>, <code>"1"</code>, and <code>"2"</code>. The columns <code>"A"</code> and <code>"B"</code> contain characters, whereas columns <code>"C"</code> and <code>"D"</code> contain integer values.</p>



<p>Now, we apply <code>get_dummies()</code> with this DataFrame:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.get_dummies(df)</pre>



<p><strong>Result:</strong></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>C</strong></td><td><strong>D</strong></td><td><strong>A_a</strong></td><td><strong>A_b</strong></td><td><strong>B_a</strong></td><td><strong>B_b</strong></td><td><strong>B_c</strong></td></tr><tr><td>0</td><td>1</td><td>4</td><td>1</td><td>0</td><td>1</td><td>0</td><td>0</td></tr><tr><td>1</td><td>2</td><td>5</td><td>0</td><td>1</td><td>0</td><td>0</td><td>1</td></tr><tr><td>2</td><td>3</td><td>6</td><td>0</td><td>1</td><td>0</td><td>1</td><td>0</td></tr></tbody></table></figure>



<p>The columns <code>"C"</code> and <code>"D"</code> remain unchanged because only columns with either &#8220;object&#8221; or &#8220;category&#8221; data type will be converted.</p>



<p>We also get two <code>"A_"</code> columns and three <code>"B_"</code> columns. That&#8217;s because in the initial data frame there are only two unique values in column <code>"A"</code> and three unique values in column <code>"B"</code>. </p>



<p>The ones and zeros in the resulting data frame are the dummy variables, just as in the examples above where we applied the <code>get_dummies()</code> function on lists. </p>



<p>For example, the <code>"1"</code> in the first row of the <code>"A_a"</code> column means that the first value from the <code>"A"</code> column in the initial data frame is the character <code>"a"</code>.</p>



<h2 class="wp-block-heading">The &#8220;columns&#8221; parameter</h2>



<p>Especially in large data frames, it might be that we only want to convert specific columns instead of converting every possible column. Therefore, we use the &#8220;<code>columns</code>&#8221; parameter which we assign the labels of the columns that we want to convert.</p>



<p>We use the data frame again that we created in the previous section:</p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>A</strong></td><td><strong>B</strong></td><td><strong>C</strong></td><td><strong>D</strong></td></tr><tr><td>0</td><td>a</td><td>a</td><td>1</td><td>4</td></tr><tr><td>1</td><td>b</td><td>c</td><td>2</td><td>5</td></tr><tr><td>2</td><td>b</td><td>b</td><td>3</td><td>6</td></tr></tbody></table></figure>



<p>But now, when applying the <code>get_dummies()</code> function, we add the &#8220;<code>columns</code>&#8221; parameter and assign it a list with the list entry <code>"B"</code> to state that we only want to get the dummy variables of this column:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.get_dummies(df, columns=['B'])</pre>



<p><strong>Result:</strong></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>A</strong></td><td><strong>C</strong></td><td><strong>D</strong></td><td><strong>B_a</strong></td><td><strong>B_b</strong></td><td><strong>B_c</strong></td></tr><tr><td>0</td><td>a</td><td>1</td><td>4</td><td>1</td><td>0</td><td>0</td></tr><tr><td>1</td><td>b</td><td>2</td><td>5</td><td>0</td><td>0</td><td>1</td></tr><tr><td>2</td><td>b</td><td>3</td><td>6</td><td>0</td><td>1</td><td>0</td></tr></tbody></table></figure>



<p>The first three columns of the resulting data frame are the unchanged columns. They are the same as in the initial data frame. </p>



<p>The columns <code>"C"</code> and <code>"D"</code> are unchanged because they are neither from the &#8220;<code>object</code>&#8221; data type nor from the &#8220;<code>category</code>&#8221; data type. </p>



<p>And <code>"A"</code> remains unchanged because we did not add it to our &#8220;<code>columns</code>&#8221; parameter&#8217;s list.</p>



<p>The last three columns in the resulting data frame are the encoded variables from column <code>"B"</code>.</p>



<p>By default, the <code>columns</code> parameter is set to <code>None</code>. This way, all columns with either &#8220;<code>object</code>&#8221; or &#8220;<code>category</code>&#8221; data type will be converted. We saw that in the previous examples where we did not set the <code>columns</code> parameter.</p>



<h2 class="wp-block-heading">Changing the Prefixes</h2>



<p>We can change the prefixes for our new columns in the resulting data frames by adding the <code>prefix</code> parameter. </p>



<p>Again, we use the data frame <code>df</code> for this purpose:</p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>A</strong></td><td><strong>B</strong></td><td><strong>C</strong></td><td><strong>D</strong></td></tr><tr><td>0</td><td>a</td><td>a</td><td>1</td><td>4</td></tr><tr><td>1</td><td>b</td><td>c</td><td>2</td><td>5</td></tr><tr><td>2</td><td>b</td><td>b</td><td>3</td><td>6</td></tr></tbody></table></figure>



<p>Now, we perform the <code>get_dummies()</code> operation on this data frame and add the <code>prefix</code> parameter which we assign a list with the prefix labels for the converted columns. </p>



<p>This list should be the same <a href="https://blog.finxter.com/python-len/" data-type="post" data-id="22386" target="_blank" rel="noreferrer noopener">length</a> as the number of columns that get converted:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.get_dummies(df, prefix=['column1', 'column2'])</pre>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>C</strong></td><td><strong>D</strong></td><td><strong>column1_a</strong></td><td><strong>column1_b</strong></td><td><strong>column2_a</strong></td><td><strong>column2_b</strong></td><td><strong>column2_c</strong></td></tr><tr><td>0</td><td>1</td><td>4</td><td>1</td><td>0</td><td>1</td><td>0</td><td>0</td></tr><tr><td>1</td><td>2</td><td>5</td><td>0</td><td>1</td><td>0</td><td>0</td><td>1</td></tr><tr><td>2</td><td>3</td><td>6</td><td>0</td><td>1</td><td>0</td><td>1</td><td>0</td></tr></tbody></table></figure>



<p>Since two columns get encoded (<code>"A"</code> and <code>"B"</code>), we apply two prefixes to the <code>prefix</code> parameter, <code>"column1"</code> and <code>"column2"</code>.</p>



<p>The resulting data frame shows the new prefixes for the encoded columns.</p>



<p>If we want to, we can also change the prefix separator by adding the <code>prefix_sep</code> parameter:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.get_dummies(df, prefix=['column1', 'column2'], prefix_sep=':')</pre>



<p><strong>Result:</strong></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>C</strong></td><td><strong>D</strong></td><td><strong>column1:a</strong></td><td><strong>column1:b</strong></td><td><strong>column2:a</strong></td><td><strong>column2:b</strong></td><td><strong>column2:c</strong></td></tr><tr><td>0</td><td>1</td><td>4</td><td>1</td><td>0</td><td>1</td><td>0</td><td>0</td></tr><tr><td>1</td><td>2</td><td>5</td><td>0</td><td>1</td><td>0</td><td>0</td><td>1</td></tr><tr><td>2</td><td>3</td><td>6</td><td>0</td><td>1</td><td>0</td><td>1</td><td>0</td></tr></tbody></table></figure>



<p>We perform the same <code>get_dummies()</code> operation as before, but we add the <code>prefix_sep</code> parameter and set it to <code>":"</code>. </p>



<p>By default, the separator is <code>"_"</code>, but we can change it to whatever we want.</p>



<h2 class="wp-block-heading">Summary</h2>



<p>All in all, we learned all about the Pandas function <code>get_dummies()</code>. </p>



<p>We learned the basic functionality of this method, how to handle <code>NaN</code> values, how to perform the function on data frames as well as lists, how to only encode specific columns, and how to set different prefixes.</p>



<p>For more tutorials about <a href="https://blog.finxter.com/pandas-quickstart/" data-type="post" data-id="16511" target="_blank" rel="noreferrer noopener">Pandas</a>, Python libraries, Python in general, or other computer science-related topics, check out the <a href="https://blog.finxter.com/email-academy/" data-type="page" data-id="12278" target="_blank" rel="noreferrer noopener">Finxter email academy</a>.</p>



<p>Happy Coding!          </p>



<p>The post <a href="https://blog.finxter.com/pandas-get_dummies-a-simple-guide-with-video/">Pandas get_dummies() &#8211; A Simple Guide with Video</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Pandas factorize() &#8211; A Simple Guide with Video</title>
		<link>https://blog.finxter.com/pandas-factorize-a-simple-guide-with-video/</link>
		
		<dc:creator><![CDATA[Luis Bruemmer]]></dc:creator>
		<pubDate>Fri, 14 Jan 2022 12:25:46 +0000</pubDate>
				<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Pandas Library]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=136106</guid>

					<description><![CDATA[<p>In this tutorial, we will learn how to apply the Pandas function factorize(). This function encodes an object as an enumerated type and determines the unique values. Here are the parameters from the official documentation: Parameter Type Description values Sequence A one-dimensional sequence. Sequences that aren’t Pandas objects are coerced to ndarrays before the factorization. ... <a title="Pandas factorize() &#8211; A Simple Guide with Video" class="read-more" href="https://blog.finxter.com/pandas-factorize-a-simple-guide-with-video/" aria-label="Read more about Pandas factorize() &#8211; A Simple Guide with Video">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/pandas-factorize-a-simple-guide-with-video/">Pandas factorize() &#8211; A Simple Guide with Video</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>In this tutorial, we will learn how to apply the <a rel="noreferrer noopener" href="https://blog.finxter.com/pandas-quickstart/" data-type="post" data-id="16511" target="_blank">Pandas</a> function <code>factorize()</code>. This function encodes an object as an <strong><em>enumerated type</em></strong> and determines the unique values.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Pandas factorize() - A Simple Guide" width="937" height="527" src="https://www.youtube.com/embed/SNo_L_Bpkoc?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>Here are the parameters from the <a href="https://pandas.pydata.org/docs/reference/api/pandas.factorize.html" target="_blank" rel="noreferrer noopener">official documentation:</a></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td><strong>Parameter</strong></td><td><strong>Type</strong></td><td><strong>Description</strong></td></tr><tr><td><code>values</code></td><td><a href="https://blog.finxter.com/iterators-iterables-and-itertools/" data-type="post" data-id="29507" target="_blank" rel="noreferrer noopener">Sequence</a></td><td>A one-dimensional sequence. Sequences that aren’t Pandas objects are coerced to <code>ndarrays</code> before the factorization.</td></tr><tr><td><code>sort</code></td><td><code><a href="https://blog.finxter.com/python-bool/" data-type="post" data-id="17841" target="_blank" rel="noreferrer noopener">bool</a></code>, default: <code>False</code></td><td><a href="https://blog.finxter.com/python-list-sort/" data-type="post" data-id="7176" target="_blank" rel="noreferrer noopener">Sort</a> the uniques and shuffle the codes to maintain the relationship.</td></tr><tr><td><code>na_sentinel</code></td><td><code><a href="https://blog.finxter.com/python-int-function/" data-type="post" data-id="22715" target="_blank" rel="noreferrer noopener">int</a></code> or <code>None</code>, default: -1</td><td>Value to mark <code>NaN</code>-values. If set to &#8220;<code>None</code>&#8220;, it will not drop the <code>NaN</code> from the <code>uniques</code> of the values.</td></tr><tr><td><code>size_hint</code></td><td><code>int</code>, optional</td><td>Hint to the hash table sizer.</td></tr><tr><td></td><td></td><td></td></tr><tr><td><strong>Returns</strong></td><td><strong>Type</strong></td><td><strong>Description</strong></td></tr><tr><td><code>codes</code></td><td><code>ndarray</code></td><td>An integer <code>ndarray</code> that’s an indexer into <code>uniques</code>.</td></tr><tr><td><code>uniques</code></td><td><code>ndarray</code>, <code>Index</code>, or<br><code>Categorical</code></td><td>The unique values. When the values are Categorical, <code>uniques</code> is a Categorical. When <code>values</code> is another Pandas object, an <code>Index</code> is returned. Otherwise, a one-dimensional <code>ndarray</code> is returned.</td></tr></tbody></table></figure>



<h2 class="wp-block-heading">The Basic Functionality of factorize()</h2>



<p>To get started, we will start with a coding example that explains how the <code>factorize()</code> function works:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pandas as pd
codes, uniques = pd.factorize(['c', 'c', 'b', 'd', 'a', 'c', 'a'])
</pre>



<p>We import the <a href="https://blog.finxter.com/how-to-install-pandas-in-python/" data-type="post" data-id="35926" target="_blank" rel="noreferrer noopener">Pandas library</a> at first. Then, we apply the <code>factorize</code> function which we assign a <a href="https://blog.finxter.com/python-lists/" data-type="post" data-id="7332" target="_blank" rel="noreferrer noopener">list</a> of characters. We set this function equal to the two variables &#8220;<code>codes</code>&#8221; and &#8220;<code>uniques</code>&#8221; because we will get two return values.</p>



<p>This is how the return values look like:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> codes
array([0, 0, 1, 2, 3, 0, 3], dtype=int64)
>>> uniques
array(['c', 'b', 'd', 'a'], dtype=object)</pre>



<p>Variable <code>codes</code> is an array that contains the numeric values from the initial list. </p>



<p>The best way to see what these numeric values represent is when we put the numeric array below the initial list:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">['c', 'c', 'b', 'd', 'a', 'c', 'a']
[0, 0, 1, 2, 3, 0, 3]</pre>



<p>We observe that the numeric values are assigned to each unique character in the original list. Since <code>"c"</code> is the first value from the original list, it is assigned the numeric value &#8220;<code>0</code>&#8221; and so on. </p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Remember</strong>: a computer program starts counting at &#8220;0&#8221;.</p>



<p>The data type for the &#8220;<code>codes</code>&#8221; array is &#8220;<code>int64</code>&#8221; because we get integer values exclusively.</p>



<p>Variable &#8220;<code>uniques</code>&#8221; shows the unique values from the initial list which are <code>"c"</code>, <code>"b"</code>, <code>"d"</code>, and <code>"a"</code>. </p>



<p>The unique values are presented in that order because they occur in that order in the initial list.</p>



<h2 class="wp-block-heading">The &#8220;sort&#8221; Parameter</h2>



<p>The list we put in the <code>factorize()</code> function in the previous section (<code>['c', 'c', 'b', 'd', 'a', 'c', 'a']</code>) represents some <a href="https://blog.finxter.com/how-to-detect-lowercase-letters-in-python/" data-type="post" data-id="26765" target="_blank" rel="noreferrer noopener">letters</a> from the alphabet. However, the letters here are not ordered alphabetically.</p>



<p>When we apply the <code>sort</code> parameter, <code>factorize()</code> outputs the list in the same order but enumerates the characters in a sorted way:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> codes, uniques = pd.factorize(['c', 'c', 'b', 'd', 'a', 'c', 'a'], sort=True)
>>> codes
array([2, 2, 1, 3, 0, 2, 0], dtype=int64)
</pre>



<p>We perform the same <code>factorize()</code> function as before, but this time, we use the <code>sort</code> parameter and set it equal to <code>True</code>.</p>



<p>Variable <code>codes</code> now shows the array with the numbers for the unique characters being alphabetically ordered. </p>



<p>For example, the <code>"c"</code> is assigned the numeric value <code>2</code> because it is the third letter in the alphabet. </p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Remember</strong>: computer programs start counting at 0, so 2 is the third value and not the second one.</p>



<p>The variable <code>uniques</code> now shows the unique values in an alphabetically sorted way:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> uniques
array(['a', 'b', 'c', 'd'], dtype=object)</pre>



<h2 class="wp-block-heading">Handling Missing Values</h2>



<p>It might be the case that we have some missing values in our list that we want to perform the <code>factorize()</code> operation on.</p>



<p>We will change our initial list by replacing one character with a <code>None</code> value. Let&#8217;s see how the <code>factorize()</code> method handles this case:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> codes, uniques = pd.factorize(['c', None, 'b', 'd', 'a', 'c', 'a'])
>>> codes
array([ 0, -1, 1, 2, 3, 0, 3], dtype=int64)
>>> uniques
array(['c', 'b', 'd', 'a'], dtype=object)</pre>



<p>The second value in the initial list is <code>None</code>. </p>



<p>In the outputted <code>codes</code> array we can see that the <code>None</code> value gets assigned the numeric value <code>-1</code>. </p>



<p>The function&#8217;s parameter <code>na_sentinel</code> is used to handle missing values. And since we do not specify this parameter here, the function takes the parameter&#8217;s default value which is <code>-1</code>.</p>



<p>However, we can change this value by applying the <code>na_sentinel</code> parameter and assigning it a custom value:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> codes, uniques = pd.factorize(['c', None, 'b', 'd', 'a', 'c', 'a'], na_sentinel=-10)
>>> codes
array([ 0, -10, 1, 2, 3, 0, 3], dtype=int64)
>>> uniques
array(['c', 'b', 'd', 'a'], dtype=object)
</pre>



<p>Here, the <code>None</code> value from the initial list was assigned the numeric value <code>-10</code> because we set <code>na_sentinel</code> equal to <code>-10</code>.  </p>



<p>In both examples, the <code>uniques</code> array was the same <code>['c', 'b', 'd', 'a']</code> because the <code>None</code> value does not count as a unique value.</p>



<p>We can also set the <code>na_sentinel</code> parameter equal to <code>None</code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> codes, uniques = pd.factorize(['c', None, 'b', 'd', 'a', 'c', 'a'], na_sentinel=None)
>>> codes
array([0, 4, 1, 2, 3, 0, 3], dtype=int64)
>>> uniques
array(['c', 'b', 'd', 'a', nan], dtype=object)</pre>



<p>Doing so, the <code>None</code> value in the initial <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="post" data-id="7332" target="_blank">list</a> gets assigned the numeric value <code>4</code> in the <code>codes</code> array. </p>



<p>That&#8217;s because by setting the <code>na_sentinel</code> parameter equal to <code>None</code> we do not drop the  <code>None</code> value, but we count it in. </p>



<p>Since the other characters <code>"c"</code>, <code>"b"</code>, <code>"d"</code>, and <code>"a"</code> get the numeric values 0, 1, 2, and 3 respectively, the <code>None</code> value gets the next numeric value which is 4. Thus, in the <code>uniques</code> array, we can find the value <code>nan</code> after the other characters.</p>



<h2 class="wp-block-heading">Factorizing Other Pandas Objects</h2>



<p>By now, we have only factorized lists. When we factorize other Pandas objects, we get a different type for <code>uniques</code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> series = pd.Series(['a', 'b', 'a', 'd'])
>>> codes, uniques = pd.factorize(series)
>>> codes
array([0, 1, 0, 2], dtype=int64)
>>> uniques
Index(['a', 'b', 'd'], dtype='object')</pre>



<p>Here, we factorize a Pandas series. </p>



<p>The resulting <code>codes</code> array is structured the same way as in the examples before since we get numeric representations for our characters combined in an array. </p>



<p>However, the <code>uniques</code> output has changed because the <a href="https://blog.finxter.com/python-type/" data-type="post" data-id="23967" target="_blank" rel="noreferrer noopener">type</a> of the output is now <code>Index</code> instead of &#8220;array&#8221; like in the examples above.</p>



<p>We can also factorize a <code>Categorical</code> object:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> category = pd.Categorical(['a', 'b', 'a', 'd'])
>>> codes, uniques = pd.factorize(category)
>>> codes
array([0, 1, 0, 2], dtype=int64)
>>> uniques
['a', 'b', 'd'] Categories (3, object): ['a', 'b', 'd']</pre>



<p>Again, the <code>codes</code> array is from the type <code>array</code> just like before. But <code>uniques</code> is now from the type <code>Categories</code>.</p>



<p>One special thing about <code>Categorical</code> happens when we assign the parameter <code>categories</code> to it:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> category = pd.Categorical(['a', 'b', 'a', 'd'], categories=['a', 'b', 'c', 'd'])
>>> codes, uniques = pd.factorize(category)
>>> codes
array([0, 1, 0, 2], dtype=int64)
>>> uniques
['a', 'b', 'd'] Categories (4, object): ['a', 'b', 'c', 'd']
</pre>



<p>We take the same characters for the factorization as in the two examples before. </p>



<p>But this time, we apply the <code>categories</code> parameter and assign it the list <code>['a', 'b', 'c', 'd']</code> to determine which categories we want to get. </p>



<p>As we can see, in the category list, there is a <code>"c"</code>. However, there is no <code>"c"</code> in the list that gets factorized <code>['a', 'b', 'a', 'd']</code>.</p>



<p>Variable <code>codes</code> remains unchanged, but <code>uniques</code> now has the <code>c</code> added to the <code>Categories</code> list although there is no <code>c</code> to be factorized.</p>



<h2 class="wp-block-heading">Summary</h2>



<p>All in all, we learned all about the Pandas function <code>factorize()</code> in this tutorial. We learned the basic functionality of this method, how to sort the values, how to handle missing values, and how to factorize different kinds of Pandas objects.</p>



<p>For more tutorials about <a href="https://blog.finxter.com/pandas-quickstart/" data-type="post" data-id="16511" target="_blank" rel="noreferrer noopener">Pandas</a>, <a href="https://blog.finxter.com/the-complete-python-library-guide/" data-type="post" data-id="3414" target="_blank" rel="noreferrer noopener">Python libraries</a>, <a href="https://blog.finxter.com/python-crash-course/" data-type="post" data-id="3951" target="_blank" rel="noreferrer noopener">Python in general</a>, or other computer science-related topics, check out the <a href="https://blog.finxter.com/email-academy/" data-type="page" data-id="12278" target="_blank" rel="noreferrer noopener">Finxter email academy</a>.</p>



<p>Happy Coding!</p>



<p>The post <a href="https://blog.finxter.com/pandas-factorize-a-simple-guide-with-video/">Pandas factorize() &#8211; A Simple Guide with Video</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Pandas merge_asof() &#8211; A Simple Guide with Video</title>
		<link>https://blog.finxter.com/pandas-merge_asof-a-simple-guide-with-video/</link>
		
		<dc:creator><![CDATA[Luis Bruemmer]]></dc:creator>
		<pubDate>Sat, 08 Jan 2022 16:36:45 +0000</pubDate>
				<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Pandas Library]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=125617</guid>

					<description><![CDATA[<p>In this tutorial, we will learn how to apply the merge_asof() function. Described in one sentence, this method performs a merge similar to a left join where we match on near keys instead of equal keys. Thus, the function is especially useful when working with time-series data. Here are the parameters from the official documentation: ... <a title="Pandas merge_asof() &#8211; A Simple Guide with Video" class="read-more" href="https://blog.finxter.com/pandas-merge_asof-a-simple-guide-with-video/" aria-label="Read more about Pandas merge_asof() &#8211; A Simple Guide with Video">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/pandas-merge_asof-a-simple-guide-with-video/">Pandas merge_asof() &#8211; A Simple Guide with Video</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Pandas merge_asof() - A Simple Guide" width="937" height="527" src="https://www.youtube.com/embed/CgH6-mNnQrA?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>In this tutorial, we will learn how to apply the <code>merge_asof()</code> function. Described in one sentence, this method performs a merge similar to a left join where we match on near keys instead of equal keys. Thus, the function is especially useful when working with time-series data.</p>



<p>Here are the parameters from the <a href="https://pandas.pydata.org/docs/reference/api/pandas.merge_asof.html" target="_blank" rel="noreferrer noopener">official documentation</a>:</p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td><strong>Parameter</strong></td><td><strong>Type</strong></td><td><strong>Description</strong></td></tr><tr><td><code>left</code></td><td>DataFrame or named Series</td><td></td></tr><tr><td><code>right</code></td><td>DataFrame or named Series</td><td></td></tr><tr><td><code>on</code></td><td>label</td><td>Field name to join on. Must be contained in both<br>DataFrames. Data must be ordered. Must be a numeric column. On or left_on/right_on must be used.</td></tr><tr><td><code>left_on</code></td><td>label</td><td>Field name to join on in the left DataFrame.</td></tr><tr><td><code>right_on</code></td><td>label</td><td>Field name to join on in the right DataFrame.</td></tr><tr><td><code>left_index</code></td><td><code><a href="https://blog.finxter.com/python-bool/" data-type="post" data-id="17841" target="_blank" rel="noreferrer noopener">bool</a></code></td><td>Use the index of the left DataFrame as the join key.</td></tr><tr><td><code>right_index</code></td><td><code>bool</code></td><td>Use the index of the right DataFrame as the join key.</td></tr><tr><td><code>by</code></td><td>column name or list of column<br>names</td><td>Match on these columns before performing the<br>merge operation.</td></tr><tr><td><code>left_by</code></td><td>column name</td><td>Field names to match on in the left DataFrame.</td></tr><tr><td><code>right_by</code></td><td>column name</td><td>Field names to match on in the right DataFrame.</td></tr><tr><td><code>suffixes</code></td><td>2-length sequence: <a href="https://blog.finxter.com/the-ultimate-guide-to-python-tuples/" data-type="post" data-id="12043" target="_blank" rel="noreferrer noopener">tuple</a>, <a href="https://blog.finxter.com/python-lists/" data-type="post" data-id="7332" target="_blank" rel="noreferrer noopener">list</a>, etc.</td><td>Suffix to apply to the overlapping column names in the left and right side, respectively.</td></tr><tr><td><code>tolerance</code></td><td><code><a href="https://blog.finxter.com/python-int-function/" data-type="post" data-id="22715" target="_blank" rel="noreferrer noopener">int</a></code> or <code>Timedelta</code>,<br>optional, default: <code>None</code></td><td>Select a tolerance within this range. Must be compatible with the merge index.</td></tr><tr><td><code>allow_exact_matches</code></td><td>bool, default <code data-enlighter-language="generic" class="EnlighterJSRAW">True</code></td><td>If set to <code>True</code>: allow matching with the same ‘<code>on</code>’ value (i.e. <a href="https://blog.finxter.com/python-less-than-or-equal-to/" data-type="post" data-id="30938">less-th</a><a href="https://blog.finxter.com/python-less-than-or-equal-to/" data-type="post" data-id="30938" target="_blank" rel="noreferrer noopener">a</a><a href="https://blog.finxter.com/python-less-than-or-equal-to/" data-type="post" data-id="30938">n-or-equal-to</a> / <a href="https://blog.finxter.com/python-greater-than-or-equal-to/" data-type="post" data-id="30888" target="_blank" rel="noreferrer noopener">greater-than-or-equal-to</a>)<br>If set to <code>False</code>: don’t match the same ‘<code>on</code>’ value (i.e., strictly <a href="https://blog.finxter.com/python-less-than/" data-type="post" data-id="30841" target="_blank" rel="noreferrer noopener">less-than</a> / strictly <a href="https://blog.finxter.com/python-greater-than/" data-type="post" data-id="30762" target="_blank" rel="noreferrer noopener">greater-than</a>).</td></tr><tr><td><code>direction</code></td><td><code>'backward'</code>, <code>'forward'</code>, or<br><code>'nearest'</code>, default: <code>'backward'</code></td><td>Whether to search for the prior, subsequent, or<br>closest matches.</td></tr><tr><td></td><td></td><td></td></tr><tr><td><strong>Returns</strong></td><td><strong>Type</strong></td><td></td></tr><tr><td>merged</td><td>DataFrame</td><td></td></tr></tbody></table></figure>



<h2 class="wp-block-heading">Basic Functionality of merge_asof()</h2>



<p>To get started, we will create two data frames &#8220;<code>df1</code>&#8221; and &#8220;<code>df2</code>&#8220;:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pandas as pd
df1 = pd.DataFrame({
        'time':[pd.Timestamp('2021-12-15 12:00:00'), 
                pd.Timestamp('2021-12-15 12:00:01'), 
                pd.Timestamp('2021-12-15 12:00:05'), 
                pd.Timestamp('2021-12-15 12:00:07'), 
                pd.Timestamp('2021-12-15 12:00:09'), 
                pd.Timestamp('2021-12-15 12:00:12')],
        'price': [12, 14, 8, 7, 11, 15]   
    })

print(df1)
</pre>



<p><strong>Output:</strong></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>time</strong></td><td><strong>price</strong></td></tr><tr><td>0</td><td>2021-12-15 12:00:00</td><td>12</td></tr><tr><td>1</td><td>2021-12-15 12:00:01</td><td>14</td></tr><tr><td>2</td><td>2021-12-15 12:00:05</td><td>8</td></tr><tr><td>3</td><td>2021-12-15 12:00:07</td><td>7</td></tr><tr><td>4</td><td>2021-12-15 12:00:09</td><td>11</td></tr><tr><td>5</td><td>2021-12-15 12:00:12</td><td>15</td></tr></tbody></table></figure>



<p>Let&#8217;s have a look at the second DataFrame:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">df2 = pd.DataFrame({
        'time':[pd.Timestamp('2021-12-15 12:00:00'), 
                pd.Timestamp('2021-12-15 12:00:02'), 
                pd.Timestamp('2021-12-15 12:00:04'), 
                pd.Timestamp('2021-12-15 12:00:08'), 
                pd.Timestamp('2021-12-15 12:00:10'), 
                pd.Timestamp('2021-12-15 12:00:11')],
        
        'price': [5, 7, 9, 12, 8, 12]   
    })

print(df2)
</pre>



<p><strong>Output:</strong></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>time</strong></td><td><strong>price</strong></td></tr><tr><td>0</td><td>2021-12-15 12:00:00</td><td>5</td></tr><tr><td>1</td><td>2021-12-15 12:00:02</td><td>7</td></tr><tr><td>2</td><td>2021-12-15 12:00:04</td><td>9</td></tr><tr><td>3</td><td>2021-12-15 12:00:08</td><td>12</td></tr><tr><td>4</td><td>2021-12-15 12:00:10</td><td>8</td></tr><tr><td>5</td><td>2021-12-15 12:00:11</td><td>12</td></tr></tbody></table></figure>



<p>Both data frames contain a &#8220;<code>time</code>&#8221; column and a &#8220;<code>price</code>&#8221; column respectively. However, the prices and timestamps from both data frames differ from each other.</p>



<p>Now that we created the data frames, we are ready to do our first <code>merge_asof()</code> operation:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.merge_asof(df1, df2, on='time')</pre>



<p><strong>Output:</strong></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>time</strong></td><td><strong>price_x</strong></td><td><strong>price_y</strong></td></tr><tr><td>0</td><td>2021-12-15 12:00:00</td><td>12</td><td>5</td></tr><tr><td>1</td><td>2021-12-15 12:00:01</td><td>14</td><td>5</td></tr><tr><td>2</td><td>2021-12-15 12:00:05</td><td>8</td><td>9</td></tr><tr><td>3</td><td>2021-12-15 12:00:07</td><td>7</td><td>9</td></tr><tr><td>4</td><td>2021-12-15 12:00:09</td><td>11</td><td>12</td></tr><tr><td>5</td><td>2021-12-15 12:00:12</td><td>15</td><td>12</td></tr><tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr></tbody></table></figure>



<p>We put three arguments inside the <code>merge_asof()</code> function. The first two arguments are the two data frames that we want to merge, &#8220;<code>df1</code>&#8221; and &#8220;<code>df2</code>&#8220;. The third argument is the &#8220;<code>on</code>&#8221; parameter which expects the label of the column that we want to merge on. We set this parameter equal to &#8220;<code>time</code>&#8220;, thus we want to merge on the &#8220;<code>time</code>&#8221; column.</p>



<p>The resulting data frame has two price columns &#8220;<code>price_x</code>&#8221; and &#8220;<code>price_y</code>&#8220;. The &#8220;<code>time</code>&#8221; column here contains the same timestamps as &#8220;<code>df1</code>&#8220;. That&#8217;s because we set this data frame as the first argument and thus the left data frame. And since the <strong>asof merge</strong> is similar to a <strong>left join</strong>, we get the values from the left data frame.</p>



<p>When we take a look at the new price columns, we observe that the &#8220;<code>price_x</code>&#8221; values equal the price values from &#8220;<code>df1</code>&#8220;. That&#8217;s also the case because &#8220;<code>df1</code>&#8221; is the left data frame.</p>



<p>The interesting column here is the &#8220;<code>price_y</code>&#8221; column. The &#8220;<code>price_y</code>&#8221; value in the first row equals the price value from &#8220;<code>df2</code>&#8221; in that same row. That&#8217;s because the first timestamps from &#8220;<code>df1</code>&#8221; and &#8220;<code>df2</code>&#8221; match (they are both <code>"2021-12-15 12:00:00"</code>). </p>



<p>However, the timestamps in the second row from both data frames differ from each other (<code>"df1": "2021-12-15 12:00:01", "df2": "2021-12-15 12:00:02"</code>). </p>



<p>The &#8220;<code>price_y</code>&#8221; value in the second row in the resulting data frame is <code>5</code> and thus unequal to the price value in &#8220;<code>df2</code>&#8221; in the same row. </p>



<p>By default, the <code>merge_asof()</code> function performs a backward search. Thus, it takes the price assigned to the backward nearest timestamp from &#8220;<code>df2</code>&#8221; (<code>"2021-12-15 12:00:00"</code>) which is <code>5</code> in this case:</p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>time</strong></td><td><strong>price</strong></td></tr><tr><td>0</td><td>2021-12-15 12:00:00</td><td>5</td></tr></tbody></table></figure>



<p>Similarly, the &#8220;<code>price_y</code>&#8221; value in the third row is <code>9</code> because the timestamps from &#8220;<code>df1</code>&#8221; and &#8220;<code>df2</code>&#8221; in that row don&#8217;t match and the function looks backward for the next value. </p>



<p>Since the timestamp for the third row in the resulting data frame is <code>"2021-12-15 12:00:05"</code>, it looks for the next value which is backward the nearest to this timestamp in &#8220;<code>df2</code>&#8220;. The backward nearest timestamp from &#8220;<code>df2</code>&#8221; is <code>"2021-12-15 12:00:04"</code>. </p>



<p>Thus, the function takes this row&#8217;s price value:</p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>time</strong></td><td><strong>price</strong></td></tr><tr><td>2</td><td>2021-12-15 12:00:04</td><td>9</td></tr></tbody></table></figure>



<h2 class="wp-block-heading">Parameter &#8220;direction&#8221;</h2>



<p>As mentioned in the previous section, the <code>merge_asof()</code> operation performs a backward search by default because the value for the <code>direction</code> parameter is automatically set to <code>"backward"</code> if not specified otherwise.</p>



<p>The other two options for the <code>direction</code> parameter are <code>"forward"</code> and <code>"nearest"</code>. We will start with <code>"forward"</code>. As the name suggests, this is the opposite of the backward search, so, we are looking for subsequent matches instead of prior ones.</p>



<p>We will perform the same <code>merge_asof()</code> operation as before, but this time, with a forward search:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.merge_asof(df1, df2, on='time', direction='forward')</pre>



<p><strong>Output:</strong></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>time</strong></td><td><strong>price_x</strong></td><td><strong>price_y</strong></td></tr><tr><td>0</td><td>2021-12-15 12:00:00</td><td>12</td><td>5.0</td></tr><tr><td>1</td><td>2021-12-15 12:00:01</td><td>14</td><td>7.0</td></tr><tr><td>2</td><td>2021-12-15 12:00:05</td><td>8</td><td>12.0</td></tr><tr><td>3</td><td>2021-12-15 12:00:07</td><td>7</td><td>12.0</td></tr><tr><td>4</td><td>2021-12-15 12:00:09</td><td>11</td><td>8.0</td></tr><tr><td>5</td><td>2021-12-15 12:00:12</td><td>15</td><td>NaN</td></tr></tbody></table></figure>



<p>And we compare it to the initial <code>merge_asof()</code> operation with a default backward search:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.merge_asof(df1, df2, on='time')</pre>



<p><strong>Output:</strong></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>time</strong></td><td><strong>price_x</strong></td><td><strong>price_y</strong></td></tr><tr><td>0</td><td>2021-12-15 12:00:00</td><td>12</td><td>5</td></tr><tr><td>1</td><td>2021-12-15 12:00:01</td><td>14</td><td>5</td></tr><tr><td>2</td><td>2021-12-15 12:00:05</td><td>8</td><td>9</td></tr><tr><td>3</td><td>2021-12-15 12:00:07</td><td>7</td><td>9</td></tr><tr><td>4</td><td>2021-12-15 12:00:09</td><td>11</td><td>12</td></tr><tr><td>5</td><td>2021-12-15 12:00:12</td><td>15</td><td>12</td></tr></tbody></table></figure>



<p>The &#8220;<code>time</code>&#8221; and &#8220;<code>price_x</code>&#8221; columns remain unchanged. However, some values in the &#8220;<code>price_y</code>&#8221; column are different now. </p>



<p>For example, the &#8220;<code>price_y</code>&#8221; value in the second row is now 7 instead of 5. The timestamp <code>"2021-12-15 12:00:01"</code> does not exist in &#8220;<code>df2</code>&#8220;, so the function now looks for the next timestamp in &#8220;<code>df2</code>&#8221; instead of the previous one. </p>



<p>The next timestamp is <code>"2021-12-15 12:00:02"</code>, so the function takes this row&#8217;s price value which is 7.</p>



<p>The last option for the &#8220;<code>direction</code>&#8221; parameter is <code>"nearest"</code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.merge_asof(df1, df2, on='time', direction='nearest')</pre>



<p><strong>Output:</strong></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>time</strong></td><td><strong>price_x</strong></td><td><strong>price_y</strong></td></tr><tr><td>0</td><td>2021-12-15 12:00:00</td><td>12</td><td>5</td></tr><tr><td>1</td><td>2021-12-15 12:00:01</td><td>14</td><td>5</td></tr><tr><td>2</td><td>2021-12-15 12:00:05</td><td>8</td><td>9</td></tr><tr><td>3</td><td>2021-12-15 12:00:07</td><td>7</td><td>12</td></tr><tr><td>4</td><td>2021-12-15 12:00:09</td><td>11</td><td>12</td></tr><tr><td>5</td><td>2021-12-15 12:00:12</td><td>15</td><td>12</td></tr></tbody></table></figure>



<p>The only value that changed here compared to the backward search is the &#8220;<code>price_y</code>&#8221; value in the fourth row which is now 12 instead of 9. </p>



<p>That&#8217;s because the <code>"nearest"</code> search looks for the closest match. The timestamp <code>"2021-12-15 12:00:07"</code> does not exist in &#8220;<code>df2</code>&#8220;, so the function looks for the timestamp that is closest to <code>"2021-12-15 12:00:07"</code>. And that is timestamp <code>"2021-12-15 12:00:08"</code>. </p>



<p>So, the function takes this row&#8217;s price value which is 12.</p>



<h2 class="wp-block-heading">Allowing Exact Matches</h2>



<p>It might be that we do not want to include exact matches in our merges, for example, if we only want to get values from unique timestamps. Therefore, we apply the &#8220;<code>allow_exact_matches</code>&#8221; parameter. This parameter expects a boolean value and is set to &#8220;<code>True</code>&#8221; by default.</p>



<p>Again, we perform the initial <code>merge_asof()</code> operation but this time with the &#8220;<code>allow_exact_matches</code>&#8221; parameter set to &#8220;<code>False</code>&#8220;:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.merge_asof(df1, df2, on='time', allow_exact_matches=False)</pre>



<p><strong>Output:</strong></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>time</strong></td><td><strong>price_x</strong></td><td><strong>price_y</strong></td></tr><tr><td>0</td><td>2021-12-15 12:00:00</td><td>12</td><td>NaN</td></tr><tr><td>1</td><td>2021-12-15 12:00:01</td><td>14</td><td>5.0</td></tr><tr><td>2</td><td>2021-12-15 12:00:05</td><td>8</td><td>9.0</td></tr><tr><td>3</td><td>2021-12-15 12:00:07</td><td>7</td><td>9.0</td></tr><tr><td>4</td><td>2021-12-15 12:00:09</td><td>11</td><td>12.0</td></tr><tr><td>5</td><td>2021-12-15 12:00:12</td><td>15</td><td>12.0</td></tr></tbody></table></figure>



<p>And we compare it to the initial <code>merge_of()</code> operation:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.merge_asof(df1, df2, on='time')</pre>



<p><strong>Output:</strong></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>time</strong></td><td><strong>price_x</strong></td><td><strong>price_y</strong></td></tr><tr><td>0</td><td>2021-12-15 12:00:00</td><td>12</td><td>5</td></tr><tr><td>1</td><td>2021-12-15 12:00:01</td><td>14</td><td>5</td></tr><tr><td>2</td><td>2021-12-15 12:00:05</td><td>8</td><td>9</td></tr><tr><td>3</td><td>2021-12-15 12:00:07</td><td>7</td><td>9</td></tr><tr><td>4</td><td>2021-12-15 12:00:09</td><td>11</td><td>12</td></tr><tr><td>5</td><td>2021-12-15 12:00:12</td><td>15</td><td>12</td></tr></tbody></table></figure>



<p>The only value that changed is the first &#8220;<code>price_y</code>&#8221; value which is &#8220;<code>NaN</code>&#8221; instead of 5. That&#8217;s because the timestamps in the first row of &#8220;<code>df1</code>&#8221; and in the one in the first row of &#8220;<code>df2</code>&#8221; match. And since we do not allow exact matches here, the resulting value is &#8220;<code>NaN</code>&#8220;.</p>



<h2 class="wp-block-heading">Selecting the Tolerance</h2>



<p>The <code>merge_asof()</code> function provides the &#8220;<code>tolerance</code>&#8221; parameter. Using this parameter, we can determine how much tolerance we want to allow between our timestamps:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.merge_asof(df1, df2, on='time', tolerance=pd.Timedelta('1s'))</pre>



<p><strong>Output:</strong></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>time</strong></td><td><strong>price_x</strong></td><td><strong>price_y</strong></td></tr><tr><td>0</td><td>2021-12-15 12:00:00</td><td>12</td><td>5.0</td></tr><tr><td>1</td><td>2021-12-15 12:00:01</td><td>14</td><td>5.0</td></tr><tr><td>2</td><td>2021-12-15 12:00:05</td><td>8</td><td>9.0</td></tr><tr><td><a>3</a></td><td>2021-12-15 12:00:07</td><td>7</td><td>NaN</td></tr><tr><td>4</td><td>2021-12-15 12:00:09</td><td>11</td><td>12.0</td></tr><tr><td>5</td><td>2021-12-15 12:00:12</td><td>15</td><td>12.0</td></tr></tbody></table></figure>



<p>The initial <code>merge_asof()</code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.merge_asof(df1, df2, on='time')</pre>



<p><strong>Output:</strong></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>time</strong></td><td><strong>price_x</strong></td><td><strong>price_y</strong></td></tr><tr><td>0</td><td>2021-12-15 12:00:00</td><td>12</td><td>5</td></tr><tr><td>1</td><td>2021-12-15 12:00:01</td><td>14</td><td>5</td></tr><tr><td>2</td><td>2021-12-15 12:00:05</td><td>8</td><td>9</td></tr><tr><td>3</td><td>2021-12-15 12:00:07</td><td>7</td><td>9</td></tr><tr><td>4</td><td>2021-12-15 12:00:09</td><td>11</td><td>12</td></tr><tr><td>5</td><td>2021-12-15 12:00:12</td><td>15</td><td>12</td></tr></tbody></table></figure>



<p>The only difference is that we apply the &#8220;<code>tolerance</code>&#8221; parameter and set it equal to a <code>Timedelta</code> of one second. </p>



<p>In the fourth row at the timestamp <code>"2021-12-15 12:00:07"</code> we find a &#8220;<code>NaN</code>&#8221; value which was 9 in the initial <code>merge_asof()</code> operation. The reason behind that is that the timestamp <code>"2021-12-15 12:00:07"</code> does not exist in &#8220;<code>df2</code>&#8220;. </p>



<p>So, the <code>merge_asof()</code> looks for the previous timestamp in &#8220;<code>df2</code>&#8220;. However, the previous timestamp is <code>"2021-12-15 12:00:04"</code> which lies not within the tolerance of one second. Thus, the price value from that row is not used. So, we get a &#8220;<code>NaN</code>&#8221; value in the resulting data frame.</p>



<h2 class="wp-block-heading">Matching by a Specific Column</h2>



<p>For this section, we will modify &#8220;<code>df1</code>&#8221; and &#8220;<code>df2</code>&#8221; a little bit:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">df1['category'] = ['A', 'A', 'A', 'A', 'B', 'B']
print(df1)</pre>



<p><strong>Output:</strong></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>time</strong></td><td><strong>price</strong></td><td><strong>category</strong></td></tr><tr><td>0</td><td>2021-12-15 12:00:00</td><td>12</td><td>A</td></tr><tr><td>1</td><td>2021-12-15 12:00:01</td><td>14</td><td>A</td></tr><tr><td>2</td><td>2021-12-15 12:00:05</td><td>8</td><td>A</td></tr><tr><td>3</td><td>2021-12-15 12:00:07</td><td>7</td><td>A</td></tr><tr><td>4</td><td>2021-12-15 12:00:09</td><td>11</td><td>B</td></tr><tr><td>5</td><td>2021-12-15 12:00:12</td><td>15</td><td>B</td></tr></tbody></table></figure>



<p>Also:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">df2['category'] = ['A', 'A', 'B', 'B', 'B', 'B']
print(df2)</pre>



<p><strong>Output:</strong></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>time</strong></td><td><strong>price</strong></td><td><strong>category</strong></td></tr><tr><td>0</td><td>2021-12-15 12:00:00</td><td>5</td><td>A</td></tr><tr><td>1</td><td>2021-12-15 12:00:02</td><td>7</td><td>A</td></tr><tr><td>2</td><td>2021-12-15 12:00:04</td><td>9</td><td>B</td></tr><tr><td>3</td><td>2021-12-15 12:00:08</td><td>12</td><td>B</td></tr><tr><td>4</td><td>2021-12-15 12:00:10</td><td>8</td><td>B</td></tr><tr><td>5</td><td>2021-12-15 12:00:11</td><td>12</td><td>B</td></tr></tbody></table></figure>



<p>We assigned both data frames a &#8220;<code>category</code>&#8221; column and added the categories &#8220;A&#8221; and &#8220;B&#8221;. Notice that the categories are different in &#8220;<code>df1</code>&#8221; and &#8220;<code>df2</code>&#8220;.</p>



<p>Now, we perform a <code>merge_asof()</code> operation again and we add the &#8220;<code>by</code>&#8221; parameter.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.merge_asof(df1, df2, on='time', by='category')</pre>



<p><strong>Result:</strong></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>time</strong></td><td><strong>price_x</strong></td><td><strong>category</strong></td><td><strong>price_y</strong></td></tr><tr><td>0</td><td>2021-12-15 12:00:00</td><td>12</td><td>A</td><td>5</td></tr><tr><td>1</td><td>2021-12-15 12:00:01</td><td>14</td><td>A</td><td>5</td></tr><tr><td>2</td><td>2021-12-15 12:00:05</td><td>8</td><td>A</td><td>7</td></tr><tr><td>3</td><td>2021-12-15 12:00:07</td><td>7</td><td>A</td><td>7</td></tr><tr><td>4</td><td>2021-12-15 12:00:09</td><td>11</td><td>B</td><td>12</td></tr><tr><td>5</td><td>2021-12-15 12:00:12</td><td>15</td><td>B</td><td>12</td></tr></tbody></table></figure>



<p>We merge the data frames on the &#8220;<code>time</code>&#8221; column and by the &#8220;<code>category</code>&#8221; column.</p>



<p>This was the initial <code>merge_as</code>of() operation:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.merge_asof(df1, df2, on='time')</pre>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>time</strong></td><td><strong>price_x</strong></td><td><strong>price_y</strong></td></tr><tr><td>0</td><td>2021-12-15 12:00:00</td><td>12</td><td>5</td></tr><tr><td>1</td><td>2021-12-15 12:00:01</td><td>14</td><td>5</td></tr><tr><td>2</td><td>2021-12-15 12:00:05</td><td>8</td><td>9</td></tr><tr><td>3</td><td>2021-12-15 12:00:07</td><td>7</td><td>9</td></tr><tr><td>4</td><td>2021-12-15 12:00:09</td><td>11</td><td>12</td></tr><tr><td>5</td><td>2021-12-15 12:00:12</td><td>15</td><td>12</td></tr></tbody></table></figure>



<p>As we can see, some &#8220;<code>price_y</code>&#8221; values have changed again. </p>



<p>For example, the value in the third row is now 7 instead of 9. The category in the third row in the resulting data frame is &#8220;<code>A</code>&#8220;.  And since the timestamp <code>"2021-12-15 12:00:05"</code> from the third row in the resulting data frame does not exist in &#8220;<code>df2</code>&#8220;, the function looks backward for the next timestamp. The next timestamp backward would be <code>"2021-12-15 12:00:04"</code> and the assigned price value for this timestamp in &#8220;<code>df2</code>&#8221; is 9. But the category for this timestamp is &#8220;<code>B</code>&#8220;. </p>



<p>However, the function looks for the next timestamp from the same category which is &#8220;<code>A</code>&#8220;. And this timestamp is <code>"2021-12-15 12:00:02"</code> with a price value of 7. Thus, the &#8220;<code>price_y</code>&#8221; value in the merged data frame in the third row is 7 and not 9.</p>



<h2 class="wp-block-heading">Summary</h2>



<p>All in all, we studied the Pandas function <code>merge_asof()</code>. We learned the basic functionality of this function, how to search in different directions, whether to allow exact matches or not, how to specify a tolerance, and how to perform <code>merge_asof()</code> by specific columns.</p>



<p>For more tutorials about <a href="https://blog.finxter.com/pandas-quickstart/" data-type="post" data-id="16511" target="_blank" rel="noreferrer noopener">Pandas</a>, Python <a href="https://blog.finxter.com/the-complete-python-library-guide/" data-type="post" data-id="3414" target="_blank" rel="noreferrer noopener">libraries</a>, <a href="https://blog.finxter.com/python-crash-course/" data-type="post" data-id="3951" target="_blank" rel="noreferrer noopener">Python</a> in general, or other computer science-related topics, check out the <a href="https://blog.finxter.com/blog/" data-type="URL" data-id="https://blog.finxter.com/blog/" target="_blank" rel="noreferrer noopener">Finxter Blog page</a>.</p>



<p>Happy Coding!</p>



<p>The post <a href="https://blog.finxter.com/pandas-merge_asof-a-simple-guide-with-video/">Pandas merge_asof() &#8211; A Simple Guide with Video</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Pandas merge_ordered() &#8211; A Simple Guide with Video</title>
		<link>https://blog.finxter.com/pandas-merge_ordered-a-simple-guide-with-video/</link>
		
		<dc:creator><![CDATA[Luis Bruemmer]]></dc:creator>
		<pubDate>Thu, 30 Dec 2021 17:47:53 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=111604</guid>

					<description><![CDATA[<p>In this tutorial, we will learn about the Pandas function merge_ordered(). This method performs a merge with optional interpolation. It is especially useful for ordered data like time series data. Syntax and Parameters Here are the parameters from the official documentation: Parameter Type Description left DataFrame right DataFrame on label or list Field names to ... <a title="Pandas merge_ordered() &#8211; A Simple Guide with Video" class="read-more" href="https://blog.finxter.com/pandas-merge_ordered-a-simple-guide-with-video/" aria-label="Read more about Pandas merge_ordered() &#8211; A Simple Guide with Video">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/pandas-merge_ordered-a-simple-guide-with-video/">Pandas merge_ordered() &#8211; A Simple Guide with Video</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>In this tutorial, we will learn about the Pandas function <code>merge_ordered()</code>. This method performs a merge with optional <a href="https://blog.finxter.com/scipy-interpolate-1d-2d-and-3d/" data-type="post" data-id="17935" target="_blank" rel="noreferrer noopener">interpolation</a>. It is especially useful for ordered data like time series data.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Pandas merge_ordered() - A Simple Guide" width="937" height="527" src="https://www.youtube.com/embed/v4jN3XEbpQg?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<h2 class="wp-block-heading">Syntax and Parameters</h2>



<p>Here are the parameters from the <a rel="noreferrer noopener" href="https://pandas.pydata.org/docs/reference/api/pandas.merge_ordered.html" target="_blank">official documentation</a>:</p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td><strong>Parameter</strong></td><td><strong>Type</strong></td><td><strong>Description</strong></td></tr><tr><td><code>left</code></td><td>DataFrame</td><td></td></tr><tr><td><code>right</code></td><td>DataFrame</td><td></td></tr><tr><td><code>on</code></td><td>label or <a href="https://blog.finxter.com/python-lists/" data-type="post" data-id="7332" target="_blank" rel="noreferrer noopener">list</a></td><td>Field names to join on. Must be contained in both<br>DataFrames.</td></tr><tr><td><code>left_on</code></td><td>label or list, or array-like</td><td>Field names to join on in the left DataFrame.</td></tr><tr><td><code>right_on</code></td><td>label or list, or array-like</td><td>Field names to join on in the right DataFrame.</td></tr><tr><td><code>left_by</code></td><td>column name or list of<br>column names</td><td>Group the left DataFrame by group columns and<br>merge piece by piece with the right DataFrame.</td></tr><tr><td><code>right_by</code></td><td>column name or list of<br>column names</td><td>Group the right DataFrame by group columns and<br>merge piece by piece with the left DataFrame.</td></tr><tr><td><code>fill_method</code></td><td><code>{'ffill', None}</code>,<br>default: <code>None</code></td><td>Interpolation method for data.</td></tr><tr><td><code>suffixes</code></td><td>list-like, default is<br>(<code>"_x"</code>, <code>"_y"</code>)</td><td>A length-2 sequence where each element is<br>optionally a string indicating the suffix to add to the overlapping column names in left and right respectively. A value of <code>None</code> instead of a string indicates that the column name from left or right should be left as it is. At least one of the values must not be <code>None</code>.</td></tr><tr><td><code>how</code></td><td><code>{'left', 'right', 'outer', 'inner'}</code>,<br>default <code>'outer'</code></td><td><code>left</code>: use keys from left data frame only<br><code>right</code>: use keys from right data frame only<br><code>outer</code>: use union of keys from both data frames<br><code>inner</code>: use intersection of keys from both data frames</td></tr><tr><td></td><td></td><td></td></tr><tr><td><strong>Returns</strong></td><td><strong>Type</strong></td><td><strong>Description</strong></td></tr><tr><td></td><td>DataFrame</td><td>The merged DataFrame output type will the be same<br>as ‘<code>left</code>’, if it is a subclass of DataFrame.</td></tr></tbody></table></figure>



<h2 class="wp-block-heading">Basic Example</h2>



<p>To get started, we will create two data frames:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pandas as pd
df1 = pd.DataFrame({
    'Date': ['15/01/2019', '16/01/2019', '17/01/2019', '18/01/2019', 
    '19/01/2019', '20/01/2019'],
    'Price': [16.7, 18.4, 20.0, 19.3, 17.1, 21.2]
    })
print(df1)</pre>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>Date</strong></td><td><strong>Price</strong></td></tr><tr><td>0</td><td>15.01.2019</td><td>16.7</td></tr><tr><td>1</td><td>16.01.2019</td><td>18.4</td></tr><tr><td>2</td><td>17.01.2019</td><td>20.0</td></tr><tr><td>3</td><td>18.01.2019</td><td>19.3</td></tr><tr><td>4</td><td>19.01.2019</td><td>17.1</td></tr><tr><td>5</td><td>20.01.2019</td><td>21.2</td></tr></tbody></table></figure>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">df2 = pd.DataFrame({
    'Date': ['15/01/2019', '17/01/2019', '18/01/2019', '20/01/2019', 
    '21/01/2019', '22/01/2019'],
    'Price': [14.6, 19.8, 21.9, 20.2, 17.4, 18.0]
})

print(df2)</pre>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>Date</strong></td><td><strong>Price</strong></td></tr><tr><td>0</td><td>15.01.2019</td><td>14.6</td></tr><tr><td>1</td><td>17.01.2019</td><td>19.8</td></tr><tr><td>2</td><td>18.01.2019</td><td>21.9</td></tr><tr><td>3</td><td>20.01.2019</td><td>20.2</td></tr><tr><td>4</td><td>21.01.2019</td><td>17.4</td></tr><tr><td>5</td><td>22.01.2019</td><td>18.0</td></tr></tbody></table></figure>



<p>Here, we import the Pandas library as the first step. Then, we create the two data frames &#8220;<code>df1</code>&#8221; and &#8220;<code>df2</code>&#8221; which contain a &#8220;<code>Date</code>&#8221; column and a &#8220;<code>Price</code>&#8221; column respectively.</p>



<p>Now that we created these data frames, in the next step we can perform our first <code>merge_ordered()</code> operation:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.merge_ordered(df1, df2, on='Date')</pre>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>Date</strong></td><td><strong>Price_x</strong></td><td><strong>Price_y</strong></td></tr><tr><td>0</td><td>15.01.2019</td><td>16.7</td><td>14.6</td></tr><tr><td>1</td><td>16.01.2019</td><td>18.4</td><td>NaN</td></tr><tr><td>2</td><td>17.01.2019</td><td>20.0</td><td>19.8</td></tr><tr><td>3</td><td>18.01.2019</td><td>19.3</td><td>21.9</td></tr><tr><td>4</td><td>19.01.2019</td><td>17.1</td><td>NaN</td></tr><tr><td>5</td><td>20.01.2019</td><td>21.2</td><td>20.2</td></tr><tr><td>6</td><td>21.01.2019</td><td>NaN</td><td>17.4</td></tr><tr><td>7</td><td>22.01.2019</td><td>NaN</td><td>18.0</td></tr></tbody></table></figure>



<p>We apply the <code>merge_ordered()</code> function and put in the two data frames as the first two arguments of the function. That&#8217;s because these are the data frames that we want to merge. The third parameter is the &#8220;<code>on</code>&#8221; parameter. This parameter expects the column or a list of columns that we want to perform the merge on. We choose the &#8220;<code>Date</code>&#8221; column here.</p>



<p>The outputted data frame is longer than each of the two initial data frames. That&#8217;s because, by default, the <code>merge_ordered()</code> function performs a so-called &#8220;<code>outer</code>&#8221; join. That means, we use the union of keys from both our data frames. Since there are eight unique dates, the resulting data frame has eight rows in total.</p>



<p>We also get two price columns: &#8220;<code>Price_x</code>&#8221; and &#8220;<code>Price_y</code>&#8220;. For each date, we get a price from the left data frame (&#8220;<code>Price_x</code>&#8220;) and the right data frame (&#8220;<code>Price_y</code>&#8220;). If there is a &#8220;<code>NaN</code>&#8221; value, that means, for this specific date, we have only one price value. For example, for the <code>"16.01.2019"</code>, we do not get a &#8220;<code>Price_y</code>&#8221; value because this date is only found in the first data frame.</p>



<h2 class="wp-block-heading">The &#8220;fill_method&#8221; parameter</h2>



<p>As we saw in the example above, there were some missing values labeled with &#8220;<code>NaN</code>&#8220;:</p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>Date</strong></td><td><strong>Price_x</strong></td><td><strong>Price_y</strong></td></tr><tr><td>0</td><td>15.01.2019</td><td>16.7</td><td>14.6</td></tr><tr><td>1</td><td>16.01.2019</td><td>18.4</td><td>NaN</td></tr><tr><td>2</td><td>17.01.2019</td><td>20.0</td><td>19.8</td></tr><tr><td>3</td><td>18.01.2019</td><td>19.3</td><td>21.9</td></tr><tr><td>4</td><td>19.01.2019</td><td>17.1</td><td>NaN</td></tr><tr><td>5</td><td>20.01.2019</td><td>21.2</td><td>20.2</td></tr><tr><td>6</td><td>21.01.2019</td><td>NaN</td><td>17.4</td></tr><tr><td>7</td><td>22.01.2019</td><td>NaN</td><td>18.0</td></tr></tbody></table></figure>



<p>We can get rid of these &#8220;<code>NaN</code>&#8221; values by replacing these values with the previous value. We achieve that by applying the &#8220;<code>fill_method</code>&#8221; parameter and assigning it to &#8220;<code>ffill</code>&#8220;:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.merge_ordered(df1, df2, on='Date', fill_method='ffill')</pre>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>Date</strong></td><td><strong>Price_x</strong></td><td><strong>Price_y</strong></td></tr><tr><td>0</td><td>15.01.2019</td><td>16.7</td><td>14.6</td></tr><tr><td>1</td><td>16.01.2019</td><td>18.4</td><td>14.6</td></tr><tr><td>2</td><td>17.01.2019</td><td>20.0</td><td>19.8</td></tr><tr><td>3</td><td>18.01.2019</td><td>19.3</td><td>21.9</td></tr><tr><td>4</td><td>19.01.2019</td><td>17.1</td><td>21.9</td></tr><tr><td>5</td><td>20.01.2019</td><td>21.2</td><td>20.2</td></tr><tr><td>6</td><td>21.01.2019</td><td>21.2</td><td>17.4</td></tr><tr><td>7</td><td>22.01.2019</td><td>21.2</td><td>18.0</td></tr></tbody></table></figure>



<p>Now, we do not have any more missing values here. For example, the &#8220;<code>NaN</code>&#8221; value in the &#8220;<code>Price_y</code>&#8221; column for the date <code>"16.01.2019"</code> was replaced with the previous value from that column (&#8220;<code>14.6</code>&#8220;).</p>



<p>If multiple values are missing directly one after the other, all missing values get replaced by the last available value. For example, the last two values from the &#8220;<code>Price_x</code>&#8221; column were missing. They were both replaced by the value of the third last row which was <code>"21.2"</code>.</p>



<h2 class="wp-block-heading">The &#8220;suffixes&#8221; parameter</h2>



<p>In the previous example, the two price columns were named &#8220;<code>Price_x</code>&#8221; and &#8220;<code>Price_y</code>&#8221; by default. However, we can change these labels by applying the &#8220;<code>suffixes</code>&#8221; parameter:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.merge_ordered(df1, df2, on='Date', fill_method='ffill', suffixes=['_leftDF', '_rightDF'])</pre>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>Date</strong></td><td><strong>Price_leftDF</strong></td><td><strong>Price_rightDF</strong></td></tr><tr><td>0</td><td>15.01.2019</td><td>16.7</td><td>14.6</td></tr><tr><td>1</td><td>16.01.2019</td><td>18.4</td><td>14.6</td></tr><tr><td>2</td><td>17.01.2019</td><td>20.0</td><td>19.8</td></tr><tr><td>3</td><td>18.01.2019</td><td>19.3</td><td>21.9</td></tr><tr><td>4</td><td>19.01.2019</td><td>17.1</td><td>21.9</td></tr><tr><td>5</td><td>20.01.2019</td><td>21.2</td><td>20.2</td></tr><tr><td>6</td><td>21.01.2019</td><td>21.2</td><td>17.4</td></tr><tr><td>7</td><td>22.01.2019</td><td>21.2</td><td>18.0</td></tr></tbody></table></figure>



<p>We performed the same <code>merge_ordered()</code> operation as before. But this time, we added the &#8220;<code>suffixes</code>&#8221; parameter and assigned it a list with the strings &#8220;<code>_leftDF</code>&#8221; and &#8220;<code>_rightDF</code>&#8220;. The two price columns in the resulting data frame are now called &#8220;<code>Price_leftDF</code>&#8221; and &#8220;<code>Price_rightDF</code>&#8220;.</p>



<p>As the name of the parameter suggests, we only change the suffixes here, not the whole label. That&#8217;s why the column labels still say &#8220;<code>Price</code>&#8221; before the suffixes because the initial column label said &#8220;<code>Price</code>&#8221; and we only added the suffixes after that label.</p>



<h2 class="wp-block-heading">The different kinds of joins</h2>



<p>As mentioned in the introduction, by default the <code>merge_ordered()</code> function performs an outer <a href="https://blog.finxter.com/python-join-list-of-dataframes/" data-type="post" data-id="9780" target="_blank" rel="noreferrer noopener">join</a>. That means we take the union of keys from both data frames.</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="282" height="150" src="https://blog.finxter.com/wp-content/uploads/2021/12/image-62.png" alt="" class="wp-image-111618"/></figure></div>



<p>But we can change that by using the &#8220;<code>how</code>&#8221; parameter.</p>



<p>Another type of join is the &#8220;inner&#8221; join which uses the intersection of keys from both data frames:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="271" height="153" src="https://blog.finxter.com/wp-content/uploads/2021/12/image-63.png" alt="" class="wp-image-111621"/></figure></div>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.merge_ordered(df1, df2, on='Date', fill_method='ffill', how='inner')</pre>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>Date</strong></td><td><strong>Price_x</strong></td><td><strong>Price_y</strong></td></tr><tr><td>0</td><td>15.01.2019</td><td>16.7</td><td>14.6</td></tr><tr><td>1</td><td>17.01.2019</td><td>20.0</td><td>19.8</td></tr><tr><td>2</td><td>18.01.2019</td><td>19.3</td><td>21.9</td></tr><tr><td>3</td><td>20.01.2019</td><td>21.2</td><td>20.2</td></tr></tbody></table></figure>



<p>That means, we only get the dates that are found in both data frames.</p>



<p>The remaining two options the &#8220;<code>how</code>&#8221; parameter provides us with are the &#8220;<code>left</code>&#8221; join and the &#8220;<code>right</code>&#8221; join. The left join uses only the keys from the left data frame.</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="284" height="144" src="https://blog.finxter.com/wp-content/uploads/2021/12/image-64.png" alt="" class="wp-image-111622"/></figure></div>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.merge_ordered(df1, df2, on='Date', fill_method='ffill', how='left')</pre>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>Date</strong></td><td><strong>Price_x</strong></td><td><strong>Price_y</strong></td></tr><tr><td>0</td><td>15.01.2019</td><td>16.7</td><td>14.6</td></tr><tr><td>1</td><td>16.01.2019</td><td>18.4</td><td>14.6</td></tr><tr><td>2</td><td>17.01.2019</td><td>20.0</td><td>19.8</td></tr><tr><td>3</td><td>18.01.2019</td><td>19.3</td><td>21.9</td></tr><tr><td>4</td><td>19.01.2019</td><td>17.1</td><td>21.9</td></tr><tr><td>5</td><td>20.01.2019</td><td>21.2</td><td>20.2</td></tr></tbody></table></figure>



<p>Whereas the right join only uses the keys from the right data frame.</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="282" height="141" src="https://blog.finxter.com/wp-content/uploads/2021/12/image-65.png" alt="" class="wp-image-111623"/></figure></div>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.merge_ordered(df1, df2, on='Date', fill_method='ffill', how='right')</pre>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>Date</strong></td><td><strong>Price_x</strong></td><td><strong>Price_y</strong></td></tr><tr><td>0</td><td>15.01.2019</td><td>16.7</td><td>14.6</td></tr><tr><td>1</td><td>17.01.2019</td><td>20.0</td><td>19.8</td></tr><tr><td>2</td><td>18.01.2019</td><td>19.3</td><td>21.9</td></tr><tr><td>3</td><td>20.01.2019</td><td>21.2</td><td>20.2</td></tr><tr><td>4</td><td>21.01.2019</td><td>21.2</td><td>17.4</td></tr><tr><td>5</td><td>22.01.2019</td><td>21.2</td><td>18.0</td></tr></tbody></table></figure>



<h2 class="wp-block-heading">Grouping by group columns</h2>



<p>For this section, we will modify &#8220;<code>df1</code>&#8221; a little bit:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">df1['Category'] = ['A', 'A', 'A', 'B', 'B', 'B']
print(df1)</pre>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>Date</strong></td><td><strong>Price</strong></td><td><strong>Category</strong></td></tr><tr><td>0</td><td>15.01.2019</td><td>16.7</td><td>A</td></tr><tr><td>1</td><td>16.01.2019</td><td>18.4</td><td>A</td></tr><tr><td>2</td><td>17.01.2019</td><td>20.0</td><td>A</td></tr><tr><td>3</td><td>18.01.2019</td><td>19.3</td><td>B</td></tr><tr><td>4</td><td>19.01.2019</td><td>17.1</td><td>B</td></tr><tr><td>5</td><td>20.01.2019</td><td>21.2</td><td>B</td></tr></tbody></table></figure>



<p>We added a column called &#8220;<code>Category</code>&#8221; and assigned the categories &#8220;<code>A</code>&#8221; or &#8220;<code>B</code>&#8221; to each row.</p>



<p>&#8220;<code>df2</code>&#8221; remains unchanged:</p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>Date</strong></td><td><strong>Price</strong></td></tr><tr><td>0</td><td>15.01.2019</td><td>14.6</td></tr><tr><td>1</td><td>17.01.2019</td><td>19.8</td></tr><tr><td>2</td><td>18.01.2019</td><td>21.9</td></tr><tr><td>3</td><td>20.01.2019</td><td>20.2</td></tr><tr><td>4</td><td>21.01.2019</td><td>17.4</td></tr><tr><td>5</td><td>22.01.2019</td><td>18.0</td></tr></tbody></table></figure>



<p>Now, we apply the &#8220;<code>left_by</code>&#8221; parameter and assign it the value column label &#8220;<code>Category</code>&#8220;:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.merge_ordered(df1, df2, on='Date', left_by="Category")</pre>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>Date</strong></td><td><strong>Price_x</strong></td><td><strong>Category</strong></td><td><strong>Price_y</strong></td></tr><tr><td>0</td><td>15.01.2019</td><td>16.7</td><td>A</td><td>14.6</td></tr><tr><td>1</td><td>16.01.2019</td><td>18.4</td><td>A</td><td>NaN</td></tr><tr><td>2</td><td>17.01.2019</td><td>20.0</td><td>A</td><td>19.8</td></tr><tr><td>3</td><td>18.01.2019</td><td>NaN</td><td>A</td><td>21.9</td></tr><tr><td>4</td><td>20.01.2019</td><td>NaN</td><td>A</td><td>20.2</td></tr><tr><td>5</td><td>21.01.2019</td><td>NaN</td><td>A</td><td>17.4</td></tr><tr><td>6</td><td>22.01.2019</td><td>NaN</td><td>A</td><td>18.0</td></tr><tr><td>7</td><td>15.01.2019</td><td>NaN</td><td>B</td><td>14.6</td></tr><tr><td>8</td><td>17.01.2019</td><td>NaN</td><td>B</td><td>19.8</td></tr><tr><td>9</td><td>18.01.2019</td><td>19.3</td><td>B</td><td>21.9</td></tr><tr><td>10</td><td>19.01.2019</td><td>17.1</td><td>B</td><td>NaN</td></tr><tr><td>11</td><td>20.01.2019</td><td>21.2</td><td>B</td><td>20.2</td></tr><tr><td>12</td><td>21.01.2019</td><td>NaN</td><td>B</td><td>17.4</td></tr><tr><td>13</td><td>22.01.2019</td><td>NaN</td><td>B</td><td>18.0</td></tr></tbody></table></figure>



<p>This way, we group the left data frame by the &#8220;<code>Category</code>&#8221; column and merge that piece by piece with the right data frame.</p>



<p>When we look at the resulting data frame, we can observe that, for example, the &#8220;<code>Price_x</code>&#8221; entry for the date <code>"18.01.2019"</code> in row 3 is &#8220;<code>NaN</code>&#8221; although there is an entry for that date in &#8220;<code>df1</code>&#8220;. However, in &#8220;<code>df1</code>&#8220;, the date is assigned to the category &#8220;<code>B</code>&#8220;. So, in the merged data frame, the &#8220;<code>Price_x</code>&#8221; value for the date <code>"18.01.2019"</code> is found in row 9 with category &#8220;<code>B</code>&#8220;.</p>



<p>If we had a group column in the right data frame, we could do the same with the &#8220;<code>right_by</code>&#8221; parameter.</p>



<h2 class="wp-block-heading">Summary</h2>



<p>All in all, we learned how to use the Pandas function <code>merge_ordered()</code>. We saw how to apply the various parameters, how to use the different types of joins, and how to group by group columns.</p>



<p>For more tutorials about Pandas, Python libraries, Python in general, or other computer science-related topics, check out the Finxter Blog page.</p>






<p>Happy Coding!</p>
<p>The post <a href="https://blog.finxter.com/pandas-merge_ordered-a-simple-guide-with-video/">Pandas merge_ordered() &#8211; A Simple Guide with Video</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Pandas merge() &#8211; A Simple Illustrated Guide with Video</title>
		<link>https://blog.finxter.com/pandas-merge/</link>
		
		<dc:creator><![CDATA[Luis Bruemmer]]></dc:creator>
		<pubDate>Sat, 18 Dec 2021 19:05:31 +0000</pubDate>
				<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Pandas Library]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=92448</guid>

					<description><![CDATA[<p>In this tutorial, we will learn about the Pandas merge() function. Described in one sentence, the merge() function is used to combine datasets in various ways. As you go through the tutorial, you can watch the following video guide for ease of understanding: Syntax and Parameters Here are the parameters from the official documentation: Parameter ... <a title="Pandas merge() &#8211; A Simple Illustrated Guide with Video" class="read-more" href="https://blog.finxter.com/pandas-merge/" aria-label="Read more about Pandas merge() &#8211; A Simple Illustrated Guide with Video">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/pandas-merge/">Pandas merge() &#8211; A Simple Illustrated Guide with Video</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>In this tutorial, we will learn about the Pandas <code>merge()</code> function. Described in one sentence, the <code>merge()</code> function is used to <strong>combine datasets in various ways</strong>.</p>



<p>As you go through the tutorial, you can watch the following video guide for ease of understanding:</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Pandas merge() – A Simple Illustrated Guide" width="937" height="527" src="https://www.youtube.com/embed/H79jYT42lgM?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<h2 class="wp-block-heading">Syntax and Parameters</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pandas.merge(left, right, how='inner', on=None, left_on=None, 
             right_on=None, left_index=False, right_index=False, 
             sort=False, suffixes=('_x', '_y'), copy=True, 
             indicator=False, validate=None)</pre>



<p>Here are the parameters from the <a href="https://pandas.pydata.org/docs/reference/api/pandas.merge.html#pandas.merge" target="_blank" rel="noreferrer noopener">official documentation</a>:</p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td><strong>Parameter</strong></td><td><strong>Type</strong></td><td><strong>Description</strong></td></tr><tr><td><code>left</code></td><td>DataFrame</td><td></td></tr><tr><td><code>right</code></td><td>DataFrame or Series</td><td>Data frame to merge with</td></tr><tr><td><code>how</code></td><td><code>{'left', 'right', 'outer',<br>'inner', 'cross'}</code>, default <code>'inner'</code></td><td>Merge type to perform:<br><strong>left</strong>: only use the keys from the left DataFrame<br><strong>right</strong>: only use the keys from the right DataFrame<br><strong>outer</strong>: use common keys from both DataFrames<br><strong>inner</strong>: use overlap of keys from both DataFrames<br><strong>cross</strong>: cartesian product from both DataFrames</td></tr><tr><td><code>on</code></td><td>label or list</td><td>Column or index level names to join on.<br>Must be contained in both DataFrames.</td></tr><tr><td><code>left_on</code></td><td>label, or list, or<br>array-like</td><td>Column or index level names to join on in the left DataFrame.</td></tr><tr><td><code>right_on</code></td><td>label, or <a href="https://blog.finxter.com/python-lists/" data-type="post" data-id="7332" target="_blank" rel="noreferrer noopener">list</a>, or<br>array-like</td><td>Column or index level names to join on in the right DataFrame.</td></tr><tr><td><code>left_index</code></td><td><code>bool</code>, default <code>False</code> </td><td>Use index from the left DataFrame as join key(s).</td></tr><tr><td><code>right_index</code></td><td><code>bool</code>, default <code>False</code> </td><td>Use index from the right DataFrame as join key(s).</td></tr><tr><td><code>sort</code></td><td><code>bool</code>, default <code>False</code></td><td>Sort the join keys lexicographically in the resulting DataFrame. If set to <code>False</code>, the order of the join keys depends on the join type.</td></tr><tr><td><code>suffixes</code></td><td>list-like, default is<br>(<code>"_x"</code>, <code>"_y"</code>)</td><td>A length-2 sequence where each element is<br>optionally a string indicating the suffix to add to overlapping column names in&nbsp;left&nbsp;and&nbsp;right&nbsp;respectively. At least one of the values must not be <code>None</code>.</td></tr><tr><td><code>copy</code></td><td><code>bool</code>, default <code>True</code></td><td>If <code>False</code>, avoid a copy if possible.</td></tr><tr><td><code>indicator</code></td><td><code>bool</code> or <code>str</code>, default<br><code>False</code></td><td>If set to <code>True</code>, adds a column to the output DataFrame called <code>"_merge"</code> containing information of the source of each row. The column can be given a different name by providing a string as argument.</td></tr><tr><td><code>validate</code></td><td><code>str</code>, optional</td><td>If used, checks if merge is of a specified type.<br>“one_to_one” or “1:1”: checks if merged keys are unique in both left and right datasets.<br>“one_to_many” or “1:m”: checks if merged keys are unique in left dataset.<br>“many_to_one” or “m:1”: checks if merged keys are unique in right dataset.<br>“many_to_many” or “m:m”: allowed, but it does not result in checks.</td></tr></tbody></table></figure>



<p>The <strong>return value</strong> of the <code>merge()</code> function is a DataFrame consisting of the two merged objects. </p>



<h2 class="wp-block-heading">Basic Example</h2>



<p>To get started, we will first create two data frames that we will be merging in several ways throughout this tutorial:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pandas as pd

df1 = pd.DataFrame({'Player': ['Jeremy', 'Alice', 'Bob', 'John', 'Mary'],
                    'Age': [31, 25, 27, 28, 21]})
df2 = pd.DataFrame({'Player': ['Alice', 'John', 'Mary'],
                    'Position': ['Pitcher', 'Catcher', 'Center Field'],
                    'Throwing Speed': [71, 80, 81]})
print(df1)
print()
print(df2)
</pre>



<p>Output:</p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>Player</strong></td><td><strong>Age</strong></td><td></td></tr><tr><td>0</td><td>Jeremy</td><td>31</td><td></td></tr><tr><td>1</td><td>Alice</td><td>25</td><td></td></tr><tr><td>2</td><td>Bob</td><td>27</td><td></td></tr><tr><td>3</td><td>John</td><td>28</td><td></td></tr><tr><td>4</td><td>Mary</td><td>21</td><td></td></tr></tbody></table></figure>



<p>&#8230; and &#8230;</p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>Player</strong></td><td><strong>Position</strong></td><td><strong>Throwing Speed</strong></td></tr><tr><td>0</td><td>Alice</td><td>Pitcher</td><td>71</td></tr><tr><td>1</td><td>John</td><td>Catcher</td><td>80</td></tr><tr><td>2</td><td>Mary</td><td>Center Field</td><td>81</td></tr></tbody></table></figure>



<p>First, we import the Pandas library. Then we create the two data frames &#8220;<code>df1</code>&#8221; and &#8220;<code data-enlighter-language="generic" class="EnlighterJSRAW">df2</code>&#8220;. The first data frame contains the player&#8217;s names of a Baseball team, as well as the player&#8217;s age.</p>



<p>The second data frame also contains a part of the player&#8217;s names of the first data frame and these player&#8217;s position and their throwing speed.</p>



<p>We finally output the data frames and see the mentioned information in a compact way.</p>



<p>Now, we apply the <code>merge()</code> function:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.merge(df1, df2, on="Player")</pre>



<p><strong>Output:</strong></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>Player</strong></td><td><strong>Age</strong></td><td><strong>Position</strong></td><td><strong>Throwing Speed</strong></td></tr><tr><td>0</td><td>Alice</td><td>25</td><td>Pitcher</td><td>71</td></tr><tr><td>1</td><td>John</td><td>28</td><td>Catcher</td><td>80</td></tr><tr><td>2</td><td>Mary</td><td>21</td><td>Center Field</td><td>81</td></tr></tbody></table></figure>



<p>The first two arguments are the names of the data frames that we want to merge. The third argument is the &#8220;<code>on</code>&#8221; parameter. The &#8220;<code>on</code>&#8221; parameter expects the column names to join on and we set it equal to &#8220;Player&#8221;.</p>



<p>Thus, Pandas merges these data frames on the &#8220;Player&#8221; column. The merged data frame only contains the players &#8220;Alice&#8221;, &#8220;John&#8221;, and &#8220;Mary&#8221; because these are the only players contained in both data frames. So, &#8220;Jeremy&#8221; and &#8220;Bob&#8221; from the first data frame are dropped.</p>



<h2 class="wp-block-heading">The &#8220;left_on&#8221; and &#8220;right_on&#8221; Parameters</h2>



<p>For this section, we will modify the data frame &#8220;<code>df2</code>&#8221; a little bit:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">df2 = pd.DataFrame({'Name': ['Alice', 'John', 'Mary'],
                    'Position': ['Pitcher', 'Catcher', 'Center Field'],
                    'Throwing Speed': [71, 80, 81]})
print(df2)
</pre>



<p><strong>Output:</strong></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>Name</strong></td><td><strong>Position</strong></td><td><strong>Throwing Speed</strong></td></tr><tr><td>0</td><td>Alice</td><td>Pitcher</td><td>71</td></tr><tr><td>1</td><td>John</td><td>Catcher</td><td>80</td></tr><tr><td>2</td><td>Mary</td><td>Center Field</td><td>81</td></tr></tbody></table></figure>



<p>The only difference is that we changed the label of the &#8220;Player&#8221; column to &#8220;Name&#8221;.</p>



<p>Now, we want to merge the data frames &#8220;<code>df1</code>&#8221; and &#8220;<code>df2</code>&#8221; again. However, we cannot do so by applying the &#8220;<code>on</code>&#8221; parameter and assigning it to &#8220;Player&#8221; since &#8220;<code>df2</code>&#8221; does not have a &#8220;Player&#8221; column anymore.</p>



<p>Therefore, we use the two parameters &#8220;<code>left_on</code>&#8221; and &#8220;<code>right_on</code>&#8220;. We set the &#8220;<code>left_on</code>&#8221; parameter equal to the column label that we want to use for merging from the first data frame and we do the same with the &#8220;<code>right_on</code>&#8221; parameter for the second data frame:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.merge(df1, df2, left_on="Player", right_on="Name")</pre>



<p><strong>Output:</strong></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>Player</strong></td><td><strong>Age</strong></td><td><strong>Name</strong></td><td><strong>Position</strong></td><td><strong>Throwing Speed</strong></td></tr><tr><td>0</td><td>Alice</td><td>25</td><td>Alice</td><td>Pitcher</td><td>71</td></tr><tr><td>1</td><td>John</td><td>28</td><td>John</td><td>Catcher</td><td>80</td></tr><tr><td>2</td><td>Mary</td><td>21</td><td>Mary</td><td>Center Field</td><td>81</td></tr></tbody></table></figure>



<p>This way, we can merge data frames by columns with different column labels.</p>



<p>Since the &#8220;Player&#8221; column and the &#8220;Name&#8221; column contain the same information, we might want to get rid of one of them:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">df = pd.merge(df1, df2, left_on="Player", right_on="Name")
df = df.drop("Name", axis=1)
print(df)</pre>



<p><strong>Output:</strong></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>Player</strong></td><td><strong>Age</strong></td><td><strong>Position</strong></td><td><strong>Throwing Speed</strong></td></tr><tr><td>0</td><td>Alice</td><td>25</td><td>Pitcher</td><td>71</td></tr><tr><td>1</td><td>John</td><td>28</td><td>Catcher</td><td>80</td></tr><tr><td>2</td><td>Mary</td><td>21</td><td>Center Field</td><td>81</td></tr></tbody></table></figure>



<p>We assign the merged data frame to a new variable called &#8220;<code>df</code>&#8221; and then we apply the <code>drop()</code> function and assign it the &#8220;Name&#8221; column. The &#8220;<code>axis</code>&#8221; parameter is set to &#8220;1&#8221; to state that we want to drop a column and not a row.</p>



<p>The outputted data frame now misses the &#8220;Name&#8221; column.</p>



<h2 class="wp-block-heading">Merge Using Different Joins</h2>



<p>In this next step, we will learn about the different types of merges and how to apply them using the &#8220;<code>how</code>&#8221; parameter.</p>



<p>Therefore, we change &#8220;<code>df2</code>&#8221; again. We rename the &#8220;Name&#8221; column back to &#8220;Player&#8221;. Also, we add two new players, &#8220;Jane&#8221; and &#8220;Mick&#8221;:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">df2 = pd.DataFrame({'Player': ['Alice', 'John', 'Mary', 
                               'Jane', 'Mick'],
                    'Position': ['Pitcher', 'Catcher', 
                                 'Center Field', 'Pitcher', 'Catcher'],
                    'Throwing Speed': [71, 80, 81, 79, 75]})
</pre>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>Player</strong></td><td><strong>Position</strong></td><td><strong>Throwing Speed</strong></td></tr><tr><td>0</td><td>Alice</td><td>Pitcher</td><td>71</td></tr><tr><td>1</td><td>John</td><td>Catcher</td><td>80</td></tr><tr><td>2</td><td>Mary</td><td>Center Field</td><td>81</td></tr><tr><td>3</td><td>Jane</td><td>Pitcher</td><td>79</td></tr><tr><td>4</td><td>Mick</td><td>Catcher</td><td>75</td></tr></tbody></table></figure>



<p>&#8220;<code>df1</code>&#8221; still looks like this:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print(df1)</pre>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>Player</strong></td><td><strong>Age</strong></td></tr><tr><td>0</td><td>Jeremy</td><td>31</td></tr><tr><td>1</td><td>Alice</td><td>25</td></tr><tr><td>2</td><td>Bob</td><td>27</td></tr><tr><td>3</td><td>John</td><td>28</td></tr><tr><td>4</td><td>Mary</td><td>21</td></tr></tbody></table></figure>



<p>We start with the so-called &#8220;inner&#8221; join.</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="348" height="182" src="https://blog.finxter.com/wp-content/uploads/2021/12/image-51.png" alt="" class="wp-image-92459" srcset="https://blog.finxter.com/wp-content/uploads/2021/12/image-51.png 348w, https://blog.finxter.com/wp-content/uploads/2021/12/image-51-300x157.png 300w" sizes="auto, (max-width: 348px) 100vw, 348px" /></figure></div>



<p>Here, we use the intersection of keys from both our data frames:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.merge(df1, df2, how="inner", on="Player")</pre>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>Player</strong></td><td><strong>Age</strong></td><td><strong>Position</strong></td><td><strong>Throwing Speed</strong></td></tr><tr><td>0</td><td>Alice</td><td>25</td><td>Pitcher</td><td>71</td></tr><tr><td>1</td><td>John</td><td>28</td><td>Catcher</td><td>80</td></tr><tr><td>2</td><td>Mary</td><td>21</td><td>Center Field</td><td>81</td></tr></tbody></table></figure>



<p>As before, we assign the &#8220;<code>on</code>&#8221; parameter the value &#8220;Player&#8221; to specify what column we want to join on. We set the &#8220;<code>how</code>&#8221; parameter equal to <code>"inner"</code> to state that we want to perform an inner join.</p>



<p>The outputted data frame contains only the players that occur in both data frames. When we compare that merge to the merge we did in the first section, we can see that they are the same. That&#8217;s because <code>"inner"</code> is the default value for the &#8220;<code>how</code>&#8221; parameter.</p>



<p>The next type of merge we are looking at is the &#8220;outer&#8221; join.</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="347" height="183" src="https://blog.finxter.com/wp-content/uploads/2021/12/image-52.png" alt="" class="wp-image-92460" srcset="https://blog.finxter.com/wp-content/uploads/2021/12/image-52.png 347w, https://blog.finxter.com/wp-content/uploads/2021/12/image-52-300x158.png 300w" sizes="auto, (max-width: 347px) 100vw, 347px" /></figure></div>



<p>The outer join is the union of keys from both our data frames:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.merge(df1, df2, how="outer", on="Player")</pre>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>Player</strong></td><td><strong>Age</strong></td><td><strong>Position</strong></td><td><strong>Throwing Speed</strong></td></tr><tr><td>0</td><td>Jeremy</td><td>31.0</td><td>NaN</td><td>NaN</td></tr><tr><td>1</td><td>Alice</td><td>25.0</td><td>Pitcher</td><td>71.0</td></tr><tr><td>2</td><td>Bob</td><td>27.0</td><td>NaN</td><td>NaN</td></tr><tr><td>3</td><td>John</td><td>28.0</td><td>Catcher</td><td>80.0</td></tr><tr><td>4</td><td>Mary</td><td>21.0</td><td>Center Field</td><td>81.0</td></tr><tr><td>5</td><td>Jane</td><td>NaN</td><td>Pitcher</td><td>79.0</td></tr><tr><td>6</td><td>Mick</td><td>NaN</td><td>Catcher</td><td>75.0</td></tr></tbody></table></figure>



<p>The data frame contains all players from both data frames. Bob, for example, has no value for position and throwing speed because he is only contained in &#8220;<code>df1</code>&#8221; where we don&#8217;t get position and throwing speed values. Similarly, Jane does not have an age value here since she is only found in &#8220;<code>df2</code>&#8221; which does not provide age information.</p>



<p>The next merge type is the <code>"left"</code> join.</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="354" height="181" src="https://blog.finxter.com/wp-content/uploads/2021/12/image-53.png" alt="" class="wp-image-92461" srcset="https://blog.finxter.com/wp-content/uploads/2021/12/image-53.png 354w, https://blog.finxter.com/wp-content/uploads/2021/12/image-53-300x153.png 300w" sizes="auto, (max-width: 354px) 100vw, 354px" /></figure></div>



<p>Here, we use the keys from the left data frame exclusively:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.merge(df1, df2, how="left", on="Player")</pre>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>Player</strong></td><td><strong>Age</strong></td><td><strong>Position</strong></td><td><strong>Throwing Speed</strong></td></tr><tr><td>0</td><td>Jeremy</td><td>31</td><td>NaN</td><td>NaN</td></tr><tr><td>1</td><td>Alice</td><td>25</td><td>Pitcher</td><td>71.0</td></tr><tr><td>2</td><td>Bob</td><td>27</td><td>NaN</td><td>NaN</td></tr><tr><td>3</td><td>John</td><td>28</td><td>Catcher</td><td>80.0</td></tr><tr><td>4</td><td>Mary</td><td>21</td><td>Center Field</td><td>81.0</td></tr></tbody></table></figure>



<p>This data frame contains all the players from the left data frame which is &#8220;<code>df1</code>&#8221; in our case. Thus, Jeremy and Bob have no position and throwing speed values.</p>



<p>The <code>"right"</code> join is similar to the left join:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="370" height="197" src="https://blog.finxter.com/wp-content/uploads/2021/12/image-54.png" alt="" class="wp-image-92462" srcset="https://blog.finxter.com/wp-content/uploads/2021/12/image-54.png 370w, https://blog.finxter.com/wp-content/uploads/2021/12/image-54-300x160.png 300w" sizes="auto, (max-width: 370px) 100vw, 370px" /></figure></div>



<p>We are using the keys from the right data frame only:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.merge(df1, df2, how="right", on="Player")</pre>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>Player</strong></td><td><strong>Age</strong></td><td><strong>Position</strong></td><td><strong>Throwing Speed</strong></td></tr><tr><td>0</td><td>Alice</td><td>25.0</td><td>Pitcher</td><td>71</td></tr><tr><td>1</td><td>John</td><td>28.0</td><td>Catcher</td><td>80</td></tr><tr><td>2</td><td>Mary</td><td>21.0</td><td>Center Field</td><td>81</td></tr><tr><td>3</td><td>Jane</td><td>NaN</td><td>Pitcher</td><td>79</td></tr><tr><td>4</td><td>Mick</td><td>NaN</td><td>Catcher</td><td>75</td></tr></tbody></table></figure>



<p>After merging, the data frame contains all the players from the right data frame which is &#8220;<code>df2</code>&#8220;. That&#8217;s why Jane and Mick have no age values here.</p>



<p>The last join, we are learning about, is a bit special. It is called &#8220;cross&#8221; join and it creates the cartesian product from both data frames while keeping the order of the keys from the left data frame:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.merge(df1, df2, how="cross")</pre>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>Player_x</strong></td><td><strong>Age</strong></td><td><strong>Player_y</strong></td><td><strong>Position</strong></td><td><strong>Throwing Speed</strong></td></tr><tr><td>0</td><td>Jeremy</td><td>31</td><td>Alice</td><td>Pitcher</td><td>71</td></tr><tr><td>1</td><td>Jeremy</td><td>31</td><td>John</td><td>Catcher</td><td>80</td></tr><tr><td>2</td><td>Jeremy</td><td>31</td><td>Mary</td><td>Center Field</td><td>81</td></tr><tr><td>3</td><td>Jeremy</td><td>31</td><td>Jane</td><td>Pitcher</td><td>79</td></tr><tr><td>4</td><td>Jeremy</td><td>31</td><td>Mick</td><td>Catcher</td><td>75</td></tr><tr><td>5</td><td>Alice</td><td>25</td><td>Alice</td><td>Pitcher</td><td>71</td></tr><tr><td>6</td><td>Alice</td><td>25</td><td>John</td><td>Catcher</td><td>80</td></tr><tr><td>7</td><td>Alice</td><td>25</td><td>Mary</td><td>Center Field</td><td>81</td></tr><tr><td>8</td><td>Alice</td><td>25</td><td>Jane</td><td>Pitcher</td><td>79</td></tr><tr><td>9</td><td>Alice</td><td>25</td><td>Mick</td><td>Catcher</td><td>75</td></tr><tr><td>10</td><td>Bob</td><td>27</td><td>Alice</td><td>Pitcher</td><td>71</td></tr><tr><td>11</td><td>Bob</td><td>27</td><td>John</td><td>Catcher</td><td>80</td></tr><tr><td>12</td><td>Bob</td><td>27</td><td>Mary</td><td>Center Field</td><td>81</td></tr><tr><td>13</td><td>Bob</td><td>27</td><td>Jane</td><td>Pitcher</td><td>79</td></tr><tr><td>14</td><td>Bob</td><td>27</td><td>Mick</td><td>Catcher</td><td>75</td></tr><tr><td>15</td><td>John</td><td>28</td><td>Alice</td><td>Pitcher</td><td>71</td></tr><tr><td>16</td><td>John</td><td>28</td><td>John</td><td>Catcher</td><td>80</td></tr><tr><td>17</td><td>John</td><td>28</td><td>Mary</td><td>Center Field</td><td>81</td></tr><tr><td>18</td><td>John</td><td>28</td><td>Jane</td><td>Pitcher</td><td>79</td></tr><tr><td>19</td><td>John</td><td>28</td><td>Mick</td><td>Catcher</td><td>75</td></tr><tr><td>20</td><td>Mary</td><td>21</td><td>Alice</td><td>Pitcher</td><td>71</td></tr><tr><td>21</td><td>Mary</td><td>21</td><td>John</td><td>Catcher</td><td>80</td></tr><tr><td>22</td><td>Mary</td><td>21</td><td>Mary</td><td>Center Field</td><td>81</td></tr><tr><td>23</td><td>Mary</td><td>21</td><td>Jane</td><td>Pitcher</td><td>79</td></tr><tr><td>24</td><td>Mary</td><td>21</td><td>Mick</td><td>Catcher</td><td>75</td></tr></tbody></table></figure>



<p>We can observe that we have two &#8220;Player&#8221; columns now, &#8220;Player_x&#8221; and &#8220;Player_y&#8221;. Each player of &#8220;<code>df2</code>&#8221; is assigned to each player of &#8220;<code>df1</code>&#8220;. Since both data frames contain five rows, the resulting data frame now has 25 rows (5&#215;5).</p>



<h2 class="wp-block-heading">The &#8220;indicator&#8221; Parameter</h2>



<p>When we merge two data frames, it might be useful to gain information about the source of the merge keys, whether they were observed only in the left data frame, only in the right data frame, or in both. Therefore, we use the &#8220;<code>indicator</code>&#8221; parameter:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.merge(df1, df2, how="outer", on="Player", indicator=True)</pre>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>Player</strong></td><td><strong>Age</strong></td><td><strong>Position</strong></td><td><strong>Throwing Speed</strong></td><td><strong>_merge</strong></td></tr><tr><td>0</td><td>Jeremy</td><td>31.0</td><td>NaN</td><td>NaN</td><td>left_only</td></tr><tr><td>1</td><td>Alice</td><td>25.0</td><td>Pitcher</td><td>71.0</td><td>both</td></tr><tr><td>2</td><td>Bob</td><td>27.0</td><td>NaN</td><td>NaN</td><td>left_only</td></tr><tr><td>3</td><td>John</td><td>28.0</td><td>Catcher</td><td>80.0</td><td>both</td></tr><tr><td>4</td><td>Mary</td><td>21.0</td><td>Center Field</td><td>81.0</td><td>both</td></tr><tr><td>5</td><td>Jane</td><td>NaN</td><td>Pitcher</td><td>79.0</td><td>right_only</td></tr><tr><td>6</td><td>Mick</td><td>NaN</td><td>Catcher</td><td>75.0</td><td>right_only</td></tr></tbody></table></figure>



<p>We perform an outer join on the &#8220;Player&#8221; column and add the &#8220;indicator&#8221; and we set it to &#8220;<code>True</code>&#8220;. This way, we get an additional column called &#8220;<code>_merge</code>&#8221; with the entries &#8220;<code>left_only</code>&#8220;, &#8220;<code>right_only</code>&#8220;, and &#8220;<code>both</code>&#8220;.</p>



<p>For example, Jeremy gets assigned the value &#8220;<code>left_only</code>&#8221; because he only appears in the left data frame &#8220;<code>df1</code>&#8220;. And Mary&#8217;s &#8220;<code>_merge</code>&#8221; value is set to &#8220;<code>both</code>&#8221; because she is found in both data frames.</p>



<h2 class="wp-block-heading">Summary</h2>



<p>In this tutorial, we learned about the Pandas function <code>merge()</code>. We learned how to perform different kinds of merges using the function&#8217;s various parameters.</p>



<p>For more tutorials about <a href="https://blog.finxter.com/pandas-quickstart/" data-type="post" data-id="16511" target="_blank" rel="noreferrer noopener">Pandas</a>, Python libraries, Python in general, or other computer science-related topics, check out the <a href="https://blog.finxter.com/blog/" data-type="URL" data-id="https://blog.finxter.com/blog/" target="_blank" rel="noreferrer noopener">Finxter Blog page</a>.</p>



<p>Happy Coding!</p>



<p>The post <a href="https://blog.finxter.com/pandas-merge/">Pandas merge() &#8211; A Simple Illustrated Guide with Video</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Pandas qcut() &#8211; A Simple Guide with Video</title>
		<link>https://blog.finxter.com/pandas-qcut-a-simple-guide-with-video/</link>
		
		<dc:creator><![CDATA[Luis Bruemmer]]></dc:creator>
		<pubDate>Tue, 14 Dec 2021 08:53:21 +0000</pubDate>
				<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Pandas Library]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=85742</guid>

					<description><![CDATA[<p>In this tutorial, we learn about the Pandas function qcut(). This function creates unequal-sized bins with the same number of samples in each bin. Here are the parameters from the official documentation: Parameter Type Description x 1d ndarray or Series q int or list of float values Number of quantiles. Alternately: array ofquantiles. labels array ... <a title="Pandas qcut() &#8211; A Simple Guide with Video" class="read-more" href="https://blog.finxter.com/pandas-qcut-a-simple-guide-with-video/" aria-label="Read more about Pandas qcut() &#8211; A Simple Guide with Video">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/pandas-qcut-a-simple-guide-with-video/">Pandas qcut() &#8211; A Simple Guide with Video</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>In this tutorial, we learn about the Pandas function <code>qcut()</code>. This function creates unequal-sized bins with the same number of samples in each bin.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Pandas qcut() - A Simple Guide" width="937" height="527" src="https://www.youtube.com/embed/H9Vrmt7sigk?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>Here are the parameters from the <a href="https://pandas.pydata.org/docs/reference/api/pandas.qcut.html#pandas.qcut" target="_blank" rel="noreferrer noopener">official documentation</a>:</p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td><strong>Parameter</strong></td><td><strong>Type</strong></td><td><strong>Description</strong></td></tr><tr><td><code>x</code></td><td>1d <code>ndarray</code> or Series</td><td></td></tr><tr><td><code>q</code></td><td><code>int</code> or <a href="https://blog.finxter.com/python-lists/" data-type="post" data-id="7332" target="_blank" rel="noreferrer noopener">list</a> of float values</td><td>Number of quantiles. Alternately: array of<br>quantiles.</td></tr><tr><td><code>labels</code></td><td>array or <code>False</code>, default: <code>None</code></td><td>Used as the labels for the resulting bins.<br>Must be of the same length as the resulting bins. If False: returns only integer indicators of the bins. If True: raises an error.</td></tr><tr><td><code>retbins</code></td><td><a href="https://blog.finxter.com/python-bool/" data-type="post" data-id="17841" target="_blank" rel="noreferrer noopener"><code>bool</code></a>, optional</td><td>Whether to return the bins/labels.</td></tr><tr><td><code>precision</code></td><td><code><a href="https://blog.finxter.com/python-int-function/" data-type="post" data-id="22715" target="_blank" rel="noreferrer noopener">int</a></code>, optional</td><td>The precision at which to store and display<br>the bin labels.</td></tr><tr><td><code>duplicates</code></td><td><code>{default 'raise', 'drop'}</code>,<br>optional</td><td>If the bin edges are not unique:<br>raise <code>ValueError</code> or drop the non-uniques.</td></tr><tr><td></td><td></td><td></td></tr><tr><td><strong>Returns</strong></td><td><strong>Type</strong></td><td><strong>Description</strong></td></tr><tr><td><code>out</code></td><td><code>Categorical</code> or <code>Series</code> or array of integers if labels is set to <code>False</code></td><td>The return type depends on the input:<br>a Series of type <code>Category</code> if input is a <code>Series</code>, else <code>Categorical</code>. Bins are represented as categories when categorical data is returned.</td></tr><tr><td><code>bins</code></td><td><code>ndarray</code> of floats</td><td>Only if <code>retbins</code> is set to <code>True</code>.</td></tr></tbody></table></figure>



<h2 class="wp-block-heading">Basic Example</h2>



<p>Let&#8217;s create a data frame that we will be using throughout the tutorial:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pandas as pd

df = pd.DataFrame({'Competitor':['Alice', 'Mary', 'John', 'Ann', 'Bob', 'Jane', 'Tom', 'Vincent', 'Ella'],
                    'Score':[1,6,11,2,9,16,5,2,19]})
print(df)</pre>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>Competitor</strong></td><td><strong>Score</strong></td></tr><tr><td>0</td><td>Alice</td><td>1</td></tr><tr><td>1</td><td>Mary</td><td>6</td></tr><tr><td>2</td><td>John</td><td>11</td></tr><tr><td>3</td><td>Ann</td><td>2</td></tr><tr><td>4</td><td>Bob</td><td>9</td></tr><tr><td>5</td><td>Jane</td><td>16</td></tr><tr><td>6</td><td>Tom</td><td>5</td></tr><tr><td>7</td><td>Vincent</td><td>2</td></tr><tr><td>8</td><td>Ella</td><td>19</td></tr></tbody></table></figure>



<p>We import the <a href="https://blog.finxter.com/pandas-quickstart/" data-type="post" data-id="16511" target="_blank" rel="noreferrer noopener">Pandas library</a> and then we <a href="https://blog.finxter.com/how-to-create-a-dataframe-in-pandas/" data-type="post" data-id="16764" target="_blank" rel="noreferrer noopener">create a Pandas data frame</a> which we assign to the variable &#8220;<code>df</code>&#8220;. The outputted data frame provides information about several competitors and a score that each competitor reached.</p>



<p>Now, we apply the <code>qcut()</code> function:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.qcut(x = df['Score'], q = 3)</pre>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td>0</td><td>(0.999, 4.0]</td></tr><tr><td>1</td><td>(4.0, 9.667]</td></tr><tr><td>2</td><td>(9.667, 19.0]</td></tr><tr><td>3</td><td>(0.999, 4.0]</td></tr><tr><td>4</td><td>(4.0, 9.667]</td></tr><tr><td>5</td><td>(9.667, 19.0]</td></tr><tr><td>6</td><td>(4.0, 9.667]</td></tr><tr><td>7</td><td>(0.999, 4.0]</td></tr><tr><td>8</td><td>(9.667, 19.0]</td></tr></tbody></table></figure>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td><code>Name: Score, dtype: category</code></td></tr><tr><td><code>Categories (3, interval[float64, right]): [(0.999, 4.0] &lt; (4.0, 9.667] &lt; (9.667, 19.0]]</code></td></tr><tr><td>&nbsp;</td></tr></tbody></table></figure>



<p>Inside the function, we put in &#8220;<code>df['Score']</code>&#8221; as the value for the parameter &#8220;<code>x</code>&#8221; to state that this is the column that we want to use to calculate the bins on. The second argument is &#8220;3&#8221; which we assign to the &#8220;<code>q</code>&#8221; parameter. This is the number of quantiles.</p>



<p>The output assigns each score to an interval. There are a few things to observe here.</p>



<p>First, we can see at the bottom of the output the intervals in order (&#8220;<code>(0.999, 4.0] &lt; (4.0, 9.667] &lt; (9.667, 19.0]</code>&#8220;). The intervals start with parenthesis and end with square brackets. That means that the left value is not included in the interval, but the right one is. For example, &#8220;0.999&#8221; is not included, whereas &#8220;4.0&#8221; is included.</p>



<p>Additionally, we can see that the intervals do not have the same size. The first interval has a size of 3, the second has a size of 5.667 and the third one has a size of 9.333. Why are the intervals these particular sizes?</p>



<p>To answer that, we have to take a look at the number of values in each interval:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.qcut(x = df['Score'], q = 3).value_counts()</pre>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td>(0.999, 4.0]</td><td>3</td></tr><tr><td>(4.0, 9.667]</td><td>3</td></tr><tr><td>(9.667, 19.0]</td><td>3</td></tr><tr><td><code>Name: score, dtype: int64</code></td></tr></tbody></table></figure>



<p>We use the <code>value_counts()</code> function to achieve that. We can see that each bin has an equal amount of values. By assigning &#8220;3&#8221; to the &#8220;<code>q</code>&#8221; parameter we state that we want to get three intervals. And each interval should contain just as many values as the others. So, the interval sizes adjust to that.</p>



<p>To make it better visible which interval belongs to which score, we create a new column for the data frame:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">df['Category'] = pd.qcut(x = df['Score'], q = 3)
print(df)</pre>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>Competitor</strong></td><td><strong>Score</strong></td><td><strong>Category</strong></td></tr><tr><td>0</td><td>Alice</td><td>1</td><td>(0.999, 4.0]</td></tr><tr><td>1</td><td>Mary</td><td>6</td><td>(4.0, 9.667]</td></tr><tr><td>2</td><td>John</td><td>11</td><td>(9.667, 19.0]</td></tr><tr><td>3</td><td>Ann</td><td>2</td><td>(0.999, 4.0]</td></tr><tr><td>4</td><td>Bob</td><td>9</td><td>(4.0, 9.667]</td></tr><tr><td>5</td><td>Jane</td><td>16</td><td>(9.667, 19.0]</td></tr><tr><td>6</td><td>Tom</td><td>5</td><td>(4.0, 9.667]</td></tr><tr><td>7</td><td>Vincent</td><td>2</td><td>(0.999, 4.0]</td></tr><tr><td>8</td><td>Ella</td><td>19</td><td>(9.667, 19.0]</td></tr></tbody></table></figure>



<p>We create a new column called &#8220;<code>Category</code>&#8221; which contains the intervals and we add it to the existing data frame.</p>



<h2 class="wp-block-heading">The &#8220;q&#8221; parameter</h2>



<p>In the previous example, we set the &#8220;<code>q</code>&#8221; parameter equal to &#8220;3&#8221;. Of course, we can also assign other values here. Apart from an integer value, we can assign this parameter a list:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.qcut(x = df['Score'], q = [0, .25, .5, .75, 1.])</pre>



<p>Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">0	(0.999, 2.0]
1	(2.0, 6.0]
2	(6.0, 11.0]
3	(0.999, 2.0]
4	(6.0, 11.0]
5	(11.0, 19.0]
6	(2.0, 6.0]
7	(0.999, 2.0]
8	(11.0, 19.0]
Name: Score, dtype: category
Categories: (4, interval[float64, right]): [(0.999, 2.0] &lt; (2.0, 6.0] &lt; (6.0, 11.0] &lt; (11.0, 19.0]]</pre>



<p>This way, we directly determine how many percent of the values are included in each interval. For example, the first interval <em>(0.999, 2.0]</em> contains the first 25% of the score values. Since the intervals we created here all have the same length of 25%, we should get an equal amount of values in each interval.</p>



<p>Let&#8217;s see if that&#8217;s the case:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.qcut(x = df['Score'], q = [0, .25, .5, .75, 1.]).value_counts()</pre>



<p>Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">(0.999, 2.0]	3
(2.0, 6.0]	2
(6.0, 11.0]	2
(11.0, 19.0]	2
Name: Score, dtype: int64
</pre>



<p>We make use of the <code>value_counts()</code> function again. As we can see, the first interval contains one value more than the other ones. That&#8217;s because we have nine scores in total and nine cannot be divided by four. Consequently, the number of values per interval cannot be the same in all intervals.</p>



<p>The distance between the quantiles in the array does not have to be even:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.qcut(x = df['Score'], q = [0, .5, .7, .85, 1.])</pre>



<p>Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">0	(0.999, 6.0]
1	(0.999, 6.0]
2	(10.2, 15.0]
3	(0.999, 6.0]
4	(6.0, 10.2]
5	(15.0, 19.0]
6	(0.999, 6.0]
7	(0.999, 6.0]
8	(15.0, 19.0]
	
Name: Score, dtype: category
Categories: (4, interval[float64, right]): [(0.999, 6.0] &lt; (6.0, 10.2] &lt; (10.2, 15.0] &lt; (15.0, 19.0]]
</pre>



<p>The first interval is way bigger than the other ones. Thus, the number of values per interval is not evenly distributed:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.qcut(x = df['Score'], q = [0, .5, .7, .85, 1.]).value_counts()</pre>



<p>Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">(0.999, 6.0]	5
(15.0, 19.0]	2
(6.0, 10.2]	1
(10.2, 15.0]	1
Name: Score, dtype: int64
</pre>



<p>As we can observe, the first interval contains the most score values.</p>



<h2 class="wp-block-heading">Determine the Interval Precision</h2>



<p>By now, the intervals we created all had a specific precision:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.qcut(x = df['Score'], q = 3)</pre>



<p>Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">0	(0.999, 4.0]
1	(4.0, 9.667]
2	(9.667, 19.0]
3	(0.999, 4.0]
4	(4.0, 9.667]
5	(9.667, 19.0]
6	(4.0, 9.667]
7	(0.999, 4.0]
8	(9.667, 19.0]
	
Name: Score, dtype: category
Categories (3, interval[float64, right]): [(0.999, 4.0] &lt; (4.0, 9.667] &lt; (9.667, 19.0]]
</pre>



<p>As we can see, there are three decimal places except for the integer values that only have &#8220;<code>.0</code>&#8221; as the decimal place.</p>



<p>We can change that precision using the &#8220;<code>precision</code>&#8221; parameter. This parameter expects an integer value which determines how many decimal places we want to get.</p>



<p>Let&#8217;s assign &#8220;5&#8221; here to get five decimal places:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.qcut(x = df['Score'], q = 3, precision=5)</pre>



<p>Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">0	(0.99999, 4.0]
1	(4.0, 9.66667]
2	(9.66667, 19.0]
3	(0.99999, 4.0]
4	(4.0, 9.66667]
5	(9.66667, 19.0]
6	(4.0, 9.66667]
7	(0.99999, 4.0]
8	(9.66667, 19.0]
		
Name: Score, dtype: category
Categories: (3, interval[float64, right]): [(0.99999, 4.0] &lt; (4.0, 9.66667] &lt; (9.66667, 19.0]]
</pre>



<p>In this manner, we create more precise intervals. How precise we should create them depends on the use case.</p>



<h2 class="wp-block-heading">Print out the bins</h2>



<p>If we want to print out the bins that we created, we apply the &#8220;<code>retbins</code>&#8221; parameter and set it to &#8220;<code>True</code>&#8220;:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.qcut(x = df['Score'],q = 3, retbins=True)</pre>



<p>Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">0	(0.999, 4.0]
1	(4.0, 9.667]
2	(9.667, 19.0]
3	(0.999, 4.0]
4	(4.0, 9.667]
5	(9.667, 19.0]
6	(4.0, 9.667]
7	(0.999, 4.0]
8	(9.667, 19.0]
	
Name: Score, dtype: category
Categories (3, interval[float64, right]): [(0.999, 4.0] &lt; (4.0, 9.667] &lt; (9.667, 19.0]]
array([1., 4., 9.66666667, 19.]))
</pre>



<p>The only difference here compared to when we did not apply the &#8220;<code>retbins</code>&#8221; parameter is the additional line &#8220;array&#8221; at the bottom of the output. Here, we get the resulting bins inside an array.</p>



<p>This can be useful especially when we assign the &#8220;<code>q</code>&#8221; parameter an integer as we did here instead of a list.</p>



<h2 class="wp-block-heading">Define labels for the categories</h2>



<p>We already saw how to create a new column to our data frame to see which score belongs to which interval:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">df['Category'] = pd.qcut(x = df['Score'], q = 3)
print(df)</pre>



<p>Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">	Competitor	Score	Category
0	Alice	1	(0.999, 4.0]
1	Mary	6	(4.0, 9.667]
2	John	11	(9.667, 19.0]
3	Ann	2	(0.999, 4.0]
4	Bob	9	(4.0, 9.667]
5	Jane	16	(9.667, 19.0]
6	Tom	5	(4.0, 9.667]
7	Vincent	2	(0.999, 4.0]
8	Ella	19	(9.667, 19.0]
</pre>



<p>This way, we get a great overview of our data. However, assigning the intervals to the scores can be a bit confusing as we do not clearly see what a good score is and what isn&#8217;t.</p>



<p>This is where the &#8220;<code>labels</code>&#8221; parameter comes into play. We can give each interval a label to categorize our data:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">df['Category'] = pd.qcut(x = df['Score'], q = 3, labels=['bad', 'good', 'exceptional'])
print(df)</pre>



<p>Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">	Competitor	Score	Category
0	Alice	1	bad
1	Mary	6	good
2	John	11	exceptional
3	Ann	2	bad
4	Bob	9	good
5	Jane	16	exceptional
6	Tom	5	good
7	Vincent	2	bad
8	Ella	19	exceptional
</pre>



<p>The &#8220;<code>labels</code>&#8221; parameter expects a list of the labels. We choose the labels <code>"bad"</code>, <code>"good"</code>, and <code>"exceptional"</code>. So, the smallest interval is assigned the label <code>"bad"</code>, the middle interval is assigned the label <code>"good"</code>, and the biggest interval is assigned the label <code>"exceptional"</code>.</p>



<p>Thus, we can categorize our data in a more user-friendly way.</p>



<h2 class="wp-block-heading">Comparison with the cut() function</h2>



<p>Chances are when you work with the <code>qcut()</code> function, you have come across the <code>cut()</code> function as well.</p>



<p>In this final section, we will see the difference between the <code>qcut()</code> and the <code>cut()</code> function.</p>



<p>Let&#8217;s refer to our initial example of the <code>qcut()</code> function where we assigned the &#8220;<code>q</code>&#8221; parameter the value &#8220;3&#8221;:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.qcut(x = df['Score'], q = 3)</pre>



<p>Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">0	(0.999, 4.0]
1	(4.0, 9.667]
2	(9.667, 19.0]
3	(0.999, 4.0]
4	(4.0, 9.667]
5	(9.667, 19.0]
6	(4.0, 9.667]
7	(0.999, 4.0]
8	(9.667, 19.0]
	
Name: Score, dtype: category
Categories (3, interval[float64, right]): [(0.999, 4.0] &lt; (4.0, 9.667] &lt; (9.667, 19.0]]
</pre>



<p>We created three quantiles in a way that each interval now contains the same amount of score values:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.qcut(x = df['Score'], q = 3).value_counts()</pre>



<p>Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">(0.999, 4.0]	3
(4.0, 9.667]	3
(9.667, 19.0]	3
Name: score, dtype: int64
</pre>



<p>Now we do essentially the same with the <code>cut()</code> function:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.cut(x = df['Score'], bins = 3)</pre>



<p>Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">0	(0.982, 7.0]
1	(0.982, 7.0]
2	(7.0, 13.0]
3	(0.982, 7.0]
4	(7.0, 13.0]
5	(13.0, 19.0]
6	(0.982, 7.0]
7	(0.982, 7.0]
8	(13.0, 19.0]
	
Name: Score, dtype: category
Categories: (3, interval[float64, right]): [(0.982, 7.0] &lt; (7.0, 13.0] &lt; (13.0, 19.0]]
</pre>



<p>The <code>cut()</code> function does not provide a &#8220;<code>q</code>&#8221; parameter, instead, it has the &#8220;<code>bins</code>&#8221; parameter which we also assign the value &#8220;3&#8221; to create three bins.</p>



<p>As we can see, the intervals are different from the ones from the <code>qcut()</code> function. Compared to the <code>qcut()</code> function, these intervals all have the same size. They are all six units long.</p>



<p>However, the number of values in each interval is different:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pd.cut(x = df['Score'], bins = 3).value_counts()</pre>



<p>Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">(0.982, 7.0]	5
(7.0, 13.0]	2
(13.0, 19.0]	2
Name: Score, dtype: int64
</pre>



<p>Thus, <code>qcut()</code> creates intervals that are not equally long but they all contain the same number of values. Whereas the <code>cut()</code> function creates equal-sized intervals that don&#8217;t necessarily have the same number of values in them.</p>



<h2 class="wp-block-heading">Summary</h2>



<p>In this tutorial, we learned about the <code>qcut()</code> function. We saw how to create intervals in several ways, how to determine the interval&#8217;s precision, how to label our categories, and we determined the differences to the <code>cut()</code> function.</p>



<p>For more tutorials about Pandas, Python libraries, Python in general, or other computer science-related topics, check out the Finxter Blog page.</p>



<p>Happy Coding!</p>



<p>The post <a href="https://blog.finxter.com/pandas-qcut-a-simple-guide-with-video/">Pandas qcut() &#8211; A Simple Guide with Video</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 
Minified using Disk

Served from: blog.finxter.com @ 2026-06-19 14:35:10 by W3 Total Cache
-->