[Tut] Python List of Tuples to DataFrame ? - Printable Version +- Sick Gaming (https://www.sickgaming.net) +-- Forum: Programming (https://www.sickgaming.net/forum-76.html) +--- Forum: Python (https://www.sickgaming.net/forum-83.html) +--- Thread: [Tut] Python List of Tuples to DataFrame ? (/thread-101011.html) |
[Tut] Python List of Tuples to DataFrame ? - xSicKxBot - 04-22-2023 Python List of Tuples to DataFrame ? <div> <div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload='{"align":"left","id":"1309624","slug":"default","valign":"top","ignore":"","reference":"auto","class":"","count":"1","legendonly":"","readonly":"","score":"5","starsonly":"","best":"5","gap":"5","greet":"Rate this post","legend":"5\/5 - (1 vote)","size":"24","title":"Python List of Tuples to DataFrame \ud83d\udc3c","width":"142.5","_legend":"{score}\/{best} - ({count} {votes})","font_factor":"1.25"}'> <div class="kksr-stars"> <div class="kksr-stars-inactive"> <div class="kksr-star" data-star="1" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="2" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="3" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="4" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="5" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> </p></div> <div class="kksr-stars-active" style="width: 142.5px;"> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> </p></div> </div> <div class="kksr-legend" style="font-size: 19.2px;"> 5/5 – (1 vote) </div> </p></div> <p class="has-global-color-8-background-color has-background"><strong>To convert a list of tuples to a Pandas DataFrame, import the <code>pandas</code> library, call the DataFrame constructor, and pass the list of tuples as the data argument such as in <code>pd.DataFrame(tuples_list, columns=['Number', 'Letter'])</code>.</strong></p> <p>Here’s a minimal example:</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 tuples_list = [(1, 'A'), (2, 'B'), (3, 'C')] df = pd.DataFrame(tuples_list, columns=['Number', 'Letter']) </pre> <p>The output of the given code will be a Pandas DataFrame with two columns, <code>'Number'</code> and <code>'Letter'</code>, as follows:</p> <pre class="wp-block-preformatted"><code> Number Letter 0 1 A 1 2 B 2 3 C</code></pre> <p>After the Panda image, let’s dive deeper into this conversion technique so you can improve your skills and learn more on Pandas’ assume capabilities! </p> <p>I’ll also show you how to convert a list of <strong><em>named </em></strong>tuples — and how to <strong><em>convert the DataFrame back to a list of tuples </em></strong>(key-value pairs). <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f447.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p> <figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="911" height="911" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-143.png" alt="" class="wp-image-1293960" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-143.png 911w, https://blog.finxter.com/wp-content/uploads/2023/04/image-143-300x300.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-143-150x150.png 150w, https://blog.finxter.com/wp-content/uploads/2023/04/image-143-768x768.png 768w" sizes="(max-width: 911px) 100vw, 911px" /></figure> <h2 class="wp-block-heading">Converting a List of Tuples to DataFrame</h2> <p>First, let’s explore how to <strong>convert a list of tuples into a DataFrame</strong> using Python’s Pandas library. <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f40d.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p> <h3 class="wp-block-heading">Using DataFrame Constructor</h3> <p>The simplest way to convert a list of tuples into a DataFrame is by using the <code>DataFrame()</code> constructor provided by the Pandas library. This method is straightforward and can be achieved in just a few lines of code. </p> <p>Here’s an example:</p> <pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="3" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pandas as pd tuple_list = [('A', 1), ('B', 2), ('C', 3)] df = pd.DataFrame(tuple_list) print(df) </pre> <p>Executing this code will create a DataFrame with the following structure:</p> </p> <figure class="wp-block-table is-style-stripes"> <table> <thead> <tr> <td>0</td> <td>1</td> </tr> </thead> <tbody> <tr> <td>A</td> <td>1</td> </tr> <tr> <td>B</td> <td>2</td> </tr> <tr> <td>C</td> <td>3</td> </tr> </tbody> </table> </figure> <h3 class="wp-block-heading">Handling Data with Column Names</h3> <p>When converting a list of tuples to a DataFrame, it’s often useful to include column names to make the data more readable and understandable. To do this, you can add the <code>columns</code> parameter when calling the <code>DataFrame()</code> constructor. </p> <p>Here’s an example:</p> <pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="4" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pandas as pd tuple_list = [('A', 1), ('B', 2), ('C', 3)] column_names = ['Letter', 'Number'] df = pd.DataFrame(tuple_list, columns=column_names) print(df) </pre> <p>With the column names specified, the resulting DataFrame will look like this:</p> <figure class="wp-block-table is-style-stripes"> <table> <thead> <tr> <td>Letter</td> <td>Number</td> </tr> </thead> <tbody> <tr> <td>A</td> <td>1</td> </tr> <tr> <td>B</td> <td>2</td> </tr> <tr> <td>C</td> <td>3</td> </tr> </tbody> </table> </figure> <p>By using the DataFrame constructor and handling data with column names, you can easily convert a list of tuples into a DataFrame that is more organized and easier to understand. Keep working with these techniques, and soon enough, you’ll be a master of DataFrames! <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f60e.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p> <h2 class="wp-block-heading">Examples and Use Cases</h2> <div class="wp-block-image"> <figure class="aligncenter size-large"><img decoding="async" loading="lazy" width="1024" height="683" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-147-1024x683.png" alt="" class="wp-image-1293964" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-147-1024x683.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/04/image-147-300x200.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-147-768x512.png 768w, https://blog.finxter.com/wp-content/uploads/2023/04/image-147.png 1168w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure> </div> <p>When working with Python, one often encounters data stored in lists of tuples. These data structures are lightweight and easy to use, but sometimes, it’s beneficial to convert them into a more structured format, such as a DataFrame <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />. In this section, we will explore some examples and use cases for converting a list of tuples into a DataFrame in Python, using the pandas library.</p> <p>Here’s a simple example that demonstrates how to create a DataFrame from a list of tuples:</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 data = [('Peter', 18, 7), ('Riff', 15, 6), ('John', 17, 8), ('Michel', 18, 7), ('Sheli', 17, 5)] df = pd.DataFrame(data, columns=['Name', 'Age', 'Score']) </pre> <p>In this example, we have a list of tuples representing student data, with each tuple containing a name, age, and score. By passing this list to the DataFrame constructor along with the column names, we can easily convert it into a DataFrame <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f680.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />.</p> <p>Consider another use case, where we need to filter and manipulate data before converting it into a DataFrame. For instance, let’s imagine we have a list of sales data, with each tuple representing an item, its price, and the number of sales:</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="">data = [('Item A', 35, 20), ('Item B', 45, 15), ('Item C', 50, 30), ('Item D', 25, 10)] </pre> <p>In this case, we can use list comprehensions to filter items with sales greater than 20 and update the price by applying a 10% discount:</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="">filtered_data = [(item, price * 0.9, sales) for item, price, sales in data if sales > 20] df = pd.DataFrame(filtered_data, columns=['Item', 'Discounted Price', 'Sales']) </pre> <p>Now, our DataFrame contains only the filtered items with the discounted prices <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f389.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />.</p> <h2 class="wp-block-heading">Python List of Named Tuples to DataFrame</h2> <div class="wp-block-image"> <figure class="aligncenter size-large"><img decoding="async" loading="lazy" width="1024" height="804" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-141-1024x804.png" alt="" class="wp-image-1293955" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-141-1024x804.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/04/image-141-300x235.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-141-768x603.png 768w, https://blog.finxter.com/wp-content/uploads/2023/04/image-141.png 1161w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure> </div> <p>Converting a list of <strong><em><a rel="noreferrer noopener" href="https://blog.finxter.com/python-namedtuple/" data-type="post" data-id="37911" target="_blank">named tuples</a></em></strong> to a DataFrame in Python can be done efficiently using the <code>pandas</code> library’s default functions as well. </p> <p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Info</strong>: A named tuple is a subclass of a tuple, which allows you to access elements by name, making it highly readable and practical for data manipulation. <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f40d.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> </p> <p>First, create a list of named tuples using Python’s built-in <code>collections</code> module. </p> <p>Let’s assume we have a list of students with their names, ages, and test scores:</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="">from collections import namedtuple Student = namedtuple('Student', ['name', 'age', 'score']) students = [ Student('Alice', 23, 89), Student('Bob', 22, 92), Student('Charlie', 24, 85) ] </pre> <p>With the list of named tuples prepared, proceed to import the pandas library and use the <code>pd.DataFrame()</code> method to convert the list to a 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="">import pandas as pd dataframe = pd.DataFrame(students, columns=Student._fields) </pre> <p>This process creates a DataFrame with columns corresponding to the named tuple fields. The final result appears as follows:</p> <pre class="wp-block-preformatted"><code> name age score 0 Alice 23 89 1 Bob 22 92 2 Charlie 24 85 </code></pre> <p>In summary, simply define the list with the named tuple structure, and then call the <code>pd.DataFrame()</code> method to create the DataFrame.</p> <h2 class="wp-block-heading">Create a List of Tuples From a DataFrame</h2> <div class="wp-block-image"> <figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="607" height="911" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-142.png" alt="" class="wp-image-1293959" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-142.png 607w, https://blog.finxter.com/wp-content/uploads/2023/04/image-142-200x300.png 200w" sizes="(max-width: 607px) 100vw, 607px" /></figure> </div> <p>When working with data in Python, you may need to convert a DataFrame <strong><em>back</em></strong> into a list of tuples.</p> <p>To begin, import the library in your Python code using <code>import pandas as pd</code>. </p> <p>Now, let’s say you have a DataFrame, and you want to extract its data as a list of tuples. The simplest approach is to use the <code>itertuples()</code> function, which is a built-in method in Pandas <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.itertuples.html" target="_blank" rel="noreferrer noopener">(source)</a>.</p> <p>To use this method, call the <code>itertuples()</code> function on the DataFrame object, and then pass the output to the <code>list()</code> function to convert it into a list: </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="">python import pandas as pd # Sample DataFrame data = {'Name': ['John', 'Alice', 'Tim'], 'Age': [28, 22, 27]} df = pd.DataFrame(data) # Convert DataFrame to list of tuples list_of_tuples = list(df.itertuples(index=False, name=None)) print(list_of_tuples) </pre> <p>This code will output: </p> <pre class="wp-block-preformatted"><code> [('John', 28), ('Alice', 22), ('Tim', 27)] </code></pre> <p>The <code>itertuples()</code> method has two optional parameters: <code>index</code> and <code>name</code>. Setting <code>index=False</code> excludes the DataFrame index from the tuples, and setting <code>name=None</code> returns regular <a rel="noreferrer noopener" href="https://blog.finxter.com/the-ultimate-guide-to-python-tuples/" data-type="post" data-id="12043" target="_blank">tuples</a> instead of <a rel="noreferrer noopener" href="https://blog.finxter.com/python-namedtuple/" data-type="post" data-id="37911" target="_blank">named tuples</a>.</p> <hr class="wp-block-separator has-alpha-channel-opacity"/> <p>So there you go! You now know how to convert a DataFrame into a list of tuples using the Pandas library in Python <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f40d.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />. To keep learning and improving your Python skills, feel free to download our cheat sheets and visit the recommended Pandas tutorial:</p> <p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/2b50.png" alt="⭐" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/pandas-quickstart/" data-type="post" data-id="16511" target="_blank" rel="noreferrer noopener">10 Minutes to Pandas (in 5 Minutes)</a></p> </div> https://www.sickgaming.net/blog/2023/04/21/python-list-of-tuples-to-dataframe-%f0%9f%90%bc/ |