<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Muhammad Cakradewa on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Cakradewa on Medium]]></description>
        <link>https://medium.com/@mdimasaacakradewa?source=rss-afa8ef4a0dbc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ivGtmSwS35mnvvZ0</url>
            <title>Stories by Muhammad Cakradewa on Medium</title>
            <link>https://medium.com/@mdimasaacakradewa?source=rss-afa8ef4a0dbc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 19:26:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mdimasaacakradewa/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Plotly: Creating a Radar Chart]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@mdimasaacakradewa/plotly-creating-a-radar-chart-9d1dff588e0e?source=rss-afa8ef4a0dbc------2"><img src="https://cdn-images-1.medium.com/max/600/1*d6Y7JhzRwubXovRuujuu5Q.png" width="600"></a></p><p class="medium-feed-snippet">Spider Chart, or Hexagonal Chart, or Star Diagram, or Radar Chart, you name it.</p><p class="medium-feed-link"><a href="https://medium.com/@mdimasaacakradewa/plotly-creating-a-radar-chart-9d1dff588e0e?source=rss-afa8ef4a0dbc------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@mdimasaacakradewa/plotly-creating-a-radar-chart-9d1dff588e0e?source=rss-afa8ef4a0dbc------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d1dff588e0e</guid>
            <category><![CDATA[plotly]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[visualization]]></category>
            <dc:creator><![CDATA[Muhammad Cakradewa]]></dc:creator>
            <pubDate>Wed, 22 Nov 2023 20:31:04 GMT</pubDate>
            <atom:updated>2023-11-22T20:31:04.538Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Pandas: Generating “Personal” Feedbacks]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@mdimasaacakradewa/generating-personal-feedbacks-806bb77f0e08?source=rss-afa8ef4a0dbc------2"><img src="https://cdn-images-1.medium.com/max/600/0*Nri5Pp1_IJO7aYkp" width="600"></a></p><p class="medium-feed-snippet">A short python pandas tutorial about retrieving random value(s) from different sheets in an excel file, in python.</p><p class="medium-feed-link"><a href="https://medium.com/@mdimasaacakradewa/generating-personal-feedbacks-806bb77f0e08?source=rss-afa8ef4a0dbc------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@mdimasaacakradewa/generating-personal-feedbacks-806bb77f0e08?source=rss-afa8ef4a0dbc------2</link>
            <guid isPermaLink="false">https://medium.com/p/806bb77f0e08</guid>
            <dc:creator><![CDATA[Muhammad Cakradewa]]></dc:creator>
            <pubDate>Sun, 12 Nov 2023 17:50:54 GMT</pubDate>
            <atom:updated>2023-11-12T17:52:40.951Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Data Cleaning: Extracting Data from Multiple Tables]]></title>
            <link>https://medium.com/@mdimasaacakradewa/data-cleaning-extracting-data-from-multiple-tables-45094144faf4?source=rss-afa8ef4a0dbc------2</link>
            <guid isPermaLink="false">https://medium.com/p/45094144faf4</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[dataframes]]></category>
            <category><![CDATA[excel]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-cleaning]]></category>
            <dc:creator><![CDATA[Muhammad Cakradewa]]></dc:creator>
            <pubDate>Thu, 02 Nov 2023 05:02:33 GMT</pubDate>
            <atom:updated>2023-11-04T21:57:51.425Z</atom:updated>
            <content:encoded><![CDATA[<p>A short python pandas tutorial about opening multiple sheets of an excel file, in python.</p><h3>Introducing the Data</h3><p>POV: You are a teacher of a certain course — in this example, a data analytics bootcamp course. You have an Excel file, containing homework scores for a few students. The scores are stored in a table; each row represents the scores for each student. The file has multiple sheets; each sheet shows the homework scores for a specific topic. We want to, say, create a report for each student, that contains the scores of all homeworks for all available topics. That means, we want to merge the scores from each sheet, for each student, and create a new table for each student — and we want to, of course, do it in python.</p><p>The original Excel file would look like this, for example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*QvOeOYvYAWvr0z5b5RHkmA.png" /></figure><p>There are names on each row, and scores for “homework 1”, “homework 2”, and “homework 3”, and you can also see different topics being described in the sheet name: “Excel”, “Python”, and “SQL”. We want to create individual tables that has all the scores for all homework for all topics for each student. Let’s go straight to python.</p><h3>Opening Excel File (including its sheets) in Python</h3><p>Always start with importing pandas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/0*n1z0TYVjxk8asym3" /><figcaption>Pandas. hehe.</figcaption></figure><p>Then open the file using a method ExcelFile like shown below. Then list all available sheets of that excel file using the method sheet_names .</p><pre>import pandas as pd<br>file = pd.ExcelFile(&quot;homeworks.xlsx&quot;)<br>subjects = file.sheet_names<br>subjects.remove(&quot;Generator&quot;)</pre><p>As shown in the first image, we have four sheets: Generator, Excel, Python, and SQL. We want to use the latter three and leave the “Generator” sheet, because it was the sheet used to generate dummy scores for all other sheets. The method ExcelFile opens the Excel file, and it needs to be saved in a variable, in this case the file . The method file.sheet_names creates a list of all sheet names. To retrieve the values as a list, we want to save it in a variable, in this case the subjects . We also want to remove the “Generator” sheet.</p><h3>Creating Score Tables for each Student</h3><p>Now to create the tables. Again, we want to create the tables for each and all of the students. That means, it is an iterated process, that is repeated for each table entry/row. To do that, we will need to use for-loop for each student names, and then iterate for each sheet of the file. The iteration should look like this:</p><pre>names = file.parse(&quot;Generator&quot;)[[&quot;First Name&quot;,&quot;Last Name&quot;]]<br>for firstname,lastname in zip(names[&quot;First Name&quot;], names[&quot;Last Name&quot;]):<br>  for i in range(3):<br>        homeworks = file.parse(subjects[i])</pre><p>For now, we just want to create a DataFrame that contains the scores for all homework for all sheet. Each student has their own DataFrame, and all the DataFrames will just be printed out in the notebook output field, along with the students’ names for each printed DataFrame. To do that, we could create an empty DataFrame, fill (append) it with the scores — each row for each sheet, and print it at the end of the loop. When the loop goes for another round, the DataFrame will be empty again and it will be filled with the scores for the next student name. It goes for all student names in the table (for all first name and last name in the record).</p><p>We want the result to look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*6PKdSw40-FwMix7lfME7jQ.png" /><figcaption>Sample result for the first two students. The output goes further down to the last student.</figcaption></figure><p>As mentioned before, we want to create an empty DataFrame on each iteration on the student name. Then we do another iteration for each student name, to open all sheets (Excel, Python, and SQL). On each sheet iteration, we open the sheet with file.parse method. Then we retrieve only the scores that belongs to the student name being iterated on. Then we append these scores as a single row to the empty DataFrame, adding a new row on each sheet iteration. After retrieving all the scores for all sheets, we want to print the student name along with the DataFrame that now contains all the score from all sheets. With a little bit of DataFrame formatting (resetting index, putting in subject names in a column, and restructuring columns), the (full) iteration code should look like this:</p><pre>names = file.parse(&quot;Generator&quot;)[[&quot;First Name&quot;,&quot;Last Name&quot;]]<br>for firstname,lastname in zip(names[&quot;First Name&quot;], names[&quot;Last Name&quot;]):<br>    df = pd.DataFrame()<br>    for i in range(3):<br>        homeworks = file.parse(subjects[i])<br>        homeworks = homeworks[(homeworks[&quot;First Name&quot;]==firstname) &amp; (homeworks[&quot;Last Name&quot;]==lastname)].drop(columns= [&quot;First Name&quot;,&quot;Last Name&quot;])<br>        df = pd.concat([df,homeworks], axis = 0)<br>    print(&quot;____________________&quot;)<br>    print(firstname, lastname)<br>    df = df.reset_index(drop=True)<br>    df[&quot;Subject&quot;] = subjects<br>    df = df[[&quot;Subject&quot;,&quot;Homework 1&quot;,&quot;Homework 2&quot;,&quot;Homework 3&quot;]]<br>    display(df)</pre><p>The result should be as shown in the sample result above, with name and score table printed for each student. There we have it, extracting values from different tables on different sheets, and create new tables from these values.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45094144faf4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Cleaning: Handling Attendance List]]></title>
            <link>https://medium.com/@mdimasaacakradewa/data-cleaning-handling-attendance-list-7e4d25269ad2?source=rss-afa8ef4a0dbc------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e4d25269ad2</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[dataframes]]></category>
            <category><![CDATA[excel]]></category>
            <category><![CDATA[data-cleaning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Muhammad Cakradewa]]></dc:creator>
            <pubDate>Thu, 28 Sep 2023 07:26:04 GMT</pubDate>
            <atom:updated>2023-11-22T23:52:10.339Z</atom:updated>
            <content:encoded><![CDATA[<p>A short python tutorial about working with pandas dataframe.</p><p>POV: Some of your coworkers in the company is taking an online training course provided by the company. You are handling the attendance list and are given a task to report the monthly attendance back to the company, to make sure the coworkers are actually taking the course. You need to calculate, how many times in the month each coworkers attended to the course, and how many sick days &amp; vacations they took. You need to do it in python, because you’ll need to generate a report later on, that contains this information, for each coworker.</p><p>The attendance list looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*tl8uf5nzOFADuTxXGIQLeQ.png" /><figcaption>Preview of the attendance list. “x” for attended, “v” for vacation, “s” for sick, and “we” for weekend.</figcaption></figure><p>That is the sample for a week, for some of the coworkers. Your data contains the date for a whole month and for 50 coworkers. Here’s a few additional information to this data:</p><ul><li>“x” means the person attended the course that day,</li><li>“v” means the person took a vacation / day off that day,</li><li>“s” means the person was sick that day,</li><li>“we” means it’s weekend and no course being held.</li></ul><p>To ease up the process of calculating the number of “x”, “v”, and “s” of each person, we need to filter out the weekends. Then we need to write the code that calculates the occurrence of each character.</p><p>The first thing to do in python is always to import the library and open the file as a dataframe.</p><pre>import pandas as pd<br>month = &quot;August 23&quot;<br>attendance = pd.read_excel(&quot;personal.xlsx&quot;, sheet_name = month)</pre><p>Once you open an excel file in python, you will see that sometimes the table — or we call it our data — isn’t as clean as we hope it would be. Sometimes you’ll see unneeded extra columns like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qKfjZOhqvW91MnhW1ePPLA.png" /><figcaption>A section of the data.</figcaption></figure><p>Here we can see, that when we transfer values with date-format in excel to pandas dataframe, it might get transformed into a longer datetime-format. And there is also the case that you get unneeded extra columns on the right, the Unnamed. But we can see that the data should actually stop at 2023–08–31, which marks the end of the month. That means we can (or we need to) remove the extra columns on the right, as well as rename the date columns into a shorter format, without the time. To do that, we can use a for loop to reformat the date labels if possible, and to remove the columns that has “Unnamed” in its label.</p><pre># preparing empty lists to save column names we want to keep/remove<br>cols, cols_to_drop = [],[]<br><br># iterating the operation for each column<br>for col in attendance.columns:<br>    # reformat the date label if possible. If not, then do nothing<br>    try:<br>        col = col.strftime(&#39;%Y-%m-%d&#39;)<br>    except:<br>        pass<br><br>    # adding the reformatted column labels to the empty list    <br>    cols.append(col)<br><br>    # marking the labels that have &quot;Unnamed&quot;, so we can drop it later<br>    if &quot;Unnamed&quot; in col:<br>        cols_to_drop.append(col)<br><br># renaming the columns with the shorter date-format<br>attendance.columns = cols</pre><p>The date labels should be formatted as a shorter date-format. It will look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XklU23zG9cFYEj1kLQKYhA.png" /><figcaption>Shorter date-format.</figcaption></figure><p>Then we want to delete (drop) the “Unnamed” columns.</p><pre># trying to drop the column one by one. I use try-except out of habit.<br>for i in cols_to_drop:<br>    try:<br>        attendance = attendance.drop(columns = [i])<br>    except:<br>        pass</pre><p>The dataframe now doesn’t have the “Unnamed” columns anymore.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*dg17FvNS8gB6nykwIJuu8w.png" /><figcaption>No more “Unnamed”.</figcaption></figure><p>Now we want to remove the weekends, to make our task easier. To do that, there are multiple approaches, and this is one of the approach I find relatively easy to understand, though not the easiest to write. The steps are:</p><ol><li>Setting up a for loop for each column.</li><li>Then setting up another for loop inside the first loop, for each item in the column.</li><li>Then checks the string in that element, if “we” is found in the string. If yes, then retrieve the column name of that item, put the name in a list, then break the loop.</li></ol><p>If you could understand it better by looking at the code, here’s the code.</p><pre># preparing the list to save the column names for the weekend<br>weekend = []<br><br># iterating for each column (col = column name)<br>for col in attendance.columns:<br>    # iterating for each item in the column (i = item/value)<br>    for i in attendance[col]:<br>        # checking if the value contains &quot;we&quot;, and it&#39;s not the &quot;Name&quot; column<br>        if (&quot;we&quot; in i) and (&quot;Name&quot; not in col):<br>            # retrieve that column name where &quot;we&quot; is found<br>            weekend.append(col)<br>            # stopping the loop if &quot;we&quot; is found in that column<br>            break<br><br># dropping the &quot;weekend&quot; columns<br>attendance = attendance.drop(columns = weekend)</pre><p>Now you won’t see the weekend dates anymore.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*62JbsVf00ZL4DpoZzIANLQ.png" /><figcaption>No more “we” in the dataframe, just “x”, “v”, and “s”.</figcaption></figure><p>The last step is calculating the occurrence of the three characters. It can be done in a single for loop. At this point, you might have realized already, that I love loops, to the point that I might overuse it sometimes, where I could’ve done it better with other methods. But on the other hand, using loops is always a good exercise. Following are the steps.</p><ol><li>Prepare three empty lists to contain the calculation result, which we want to add to the dataframe later on.</li><li>Do for loop for each row, which also means for each coworker.</li><li>For each of the loop, we take only a row with all of the columns, excluding the name columns.</li><li>Rename the columns into “date” and “x”. It is optional and the column names are up to personal preferences.</li><li>Calculate the sum of the occurrence for each characters, and convert it to percentage (optional)</li><li>Append the numbers to the prepared lists for each character.</li><li>Create new columns to store the percentage of the attendance, vacations, and sick (x/v/s).</li></ol><p>Let’s break down the calculation steps a little bit.</p><p>In number 3, you want to take only a single row, and all columns except the first two columns (first name and last name). You can select a section of the complete dataframe by using the iloc method.</p><pre>data = attendance.iloc[0,2:]</pre><p>It will give us this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/1*ziW7q57avkCAYkl9WGrigw.png" /><figcaption>Array of values, with the “date” being the index.</figcaption></figure><p>The number(s) before the comma indicates the index of the row we want to pick, and the number(s) after the comma indicates the column number e want to pick. 0 means we take the first row, while “2:” means we take all columns starting from the 3rd column from the left.</p><p>Notice that it is still formatted as an array, which means we don’t really have them in a dataframe. Let’s see the difference when we create a dataframe from that array.</p><pre>data = pd.DataFrame(attendance.iloc[0,2:])</pre><p>It will look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/195/1*qjL128Hf6KQs1eaR0w1NZw.png" /></figure><p>Notice that the column name is “0”, which indicates that it was originally the first row. We want to do a for loop for all rows, which means the column name will always change as we run the loop through other rows, and we don’t want that. We need to rename the columns so whichever row we are working on, the label stays the same.</p><pre>data.columns = [&quot;date&quot;,&quot;x&quot;]</pre><p>Now we can count the sum of the “x” in that column, by using this.</p><pre>(data[&quot;x&quot;]== &quot;x&quot;).sum()</pre><p>And to calculate the percentage, we divide this sum with the total values in that column, and multiply with 100 afterwards.</p><pre>(data[&quot;x&quot;] == &#39;x&#39;).sum()/len(data)*100)</pre><p>Python calculates the numbers as float (decimal numbers) by default, which means our result will have a few digits behind the comma. We also want to round the number to 1 to 2 digits after comma, while we’re at it.</p><pre># 1 is the number of digits behind the comma. we can change it with any number<br>round(((data[&quot;x&quot;] == &#39;x&#39;).sum()/len(data)*100),1)</pre><p>A little extra for our calculation result is giving a “%” symbol after the result. In order to do that, we need to convert our number into text, or from float to string. This is how we do it.</p><pre>str(round(((data[&quot;x&quot;] == &#39;x&#39;).sum()/len(data)*100),1))</pre><p>You’ll see more and more brackets as we do more operations, but it’s fine. Lastly, add a “%” symbol to that string, and save the result to a variable.</p><pre>x = str(round(((data[&quot;x&quot;] == &#39;x&#39;).sum()/len(data)*100),1))+&quot;%&quot;</pre><p>Now that we covered all steps we need to operate for a single row, we can set a for loop to do these steps for all rows. It starts with preparing three empty lists, then combine the codes above all inside the for loop. It should look like this.</p><pre># preparing empty lists<br>total_x, total_v, total_s = [],[],[]<br><br># starting the for loop<br>for i in range(len(attendance)):<br>    # basically the codes we wrote above<br>    data = pd.DataFrame(attendance.iloc[i,2:].T).reset_index()<br>    data.columns = [&quot;date&quot;,&quot;x&quot;]<br>    x = str(round(((data[&quot;x&quot;] == &#39;x&#39;).sum()/len(data)*100),1))+&quot;%&quot;<br>    v = (data[&quot;x&quot;] == &quot;v&quot;).sum()<br>    s = (data[&quot;x&quot;] == &quot;s&quot;).sum()<br>    total_x.append(x)<br>    total_v.append(v)<br>    total_s.append(s)<br>attendance[&quot;attendance_rate&quot;] = total_x<br>attendance[&quot;num_of_vacation_days&quot;] = total_v<br>attendance[&quot;num_of_sick_days&quot;] = total_s</pre><p>Notice that we don’t write the row number anymore, but instead we use i for the loop iterator, indicating the number of rows for all the rows in the attendance . After the loop ends, we will have our lists filled with the percentage of “x” as well as the number of days for “v” and “s” for each coworker. We can put those lists as columns in the dataframe, to make the next steps easier. The data will look like this at the end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t5AYe-mS8Cbl2u3v-7qT8g.png" /><figcaption>completed dataframe, with three new columns on the right side.</figcaption></figure><p>That marks the end of this tutorial. This article is a part of a bigger project and is connected to other tutorials, which will be posted in other articles. I hope this article can be of use to you. Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e4d25269ad2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying Data Management with Streamlit]]></title>
            <link>https://medium.com/@mdimasaacakradewa/simplifying-data-management-with-streamlit-1147df9d362e?source=rss-afa8ef4a0dbc------2</link>
            <guid isPermaLink="false">https://medium.com/p/1147df9d362e</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[data-management]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Muhammad Cakradewa]]></dc:creator>
            <pubDate>Wed, 20 Sep 2023 10:00:59 GMT</pubDate>
            <atom:updated>2023-09-20T17:09:07.593Z</atom:updated>
            <content:encoded><![CDATA[<h4>Motivation</h4><p>For those who have yet to experience the power of Streamlit, this versatile Python library excels in crafting user-friendly web applications for data visualization and manipulation. Its key strength lies in its seamless interactivity, not only between the user and the dashboard but also with the underlying data. By leveraging Python code in the background and harnessing other complementary libraries and tools, Streamlit empowers users to effortlessly display, visualize, manipulate, explore, analyze, and dynamically modify data in real-time.</p><p>Streamlit’s development team continually introduces new features and user interfaces, further enhancing its prowess as a tool applicable across a wide spectrum of domains, including logistics, finance, healthcare, and more. Whether you’re a data scientist, a business analyst, or simply someone seeking data-driven insights, Streamlit’s expanding toolkit enables you to create intuitive, interactive, and impactful web applications, all using Python as your programming language.</p><p>In this article, we’ll demonstrate how to build a Streamlit app that simulates an inventory manager. This app allows users to add items to a “shopping cart” before committing those changes to the actual CSV data. In a future article, we’ll delve deeper into real-time data updates using Snowflake. But for now, let’s start with the basics by creating a shopping cart.</p><p>Note that the code snippets will be written in separate code boxes, but you will also find the combined version of the code snippets at the end of the code. If you just want to copy the whole code and learn it yourself, or directly use them, feel free to scroll down to the last part. I combined the snippets to avoid potential errors caused by misplaced indentations.</p><p>To experience the web app itself, you can go directly to this <a href="https://mdimasaac-inventory-management-01-main-ae58qi.streamlit.app/">link</a>.</p><h4>Part 1 — Value Entry Using Streamlit Features</h4><p>In this section, we will focus on the initial setup of our Streamlit web app, which allows users to interactively enter values into the application. Specifically, we will begin by implementing a drop-down menu (referred to as selectbox) that enables users to choose product categories. This feature enhances the user’s ability to locate specific products from a vast inventory of thousands of items.</p><p><strong>Importing Libraries</strong></p><p>To kick off our Streamlit development journey, we’ll start by importing the necessary Python libraries. These libraries will provide us with the tools and functions we need to create our interactive inventory manager.</p><pre># importing libraries<br>import pandas as pd<br>import streamlit as st</pre><p><strong>Setting a Wide Page Layout</strong></p><p>Streamlit allows us to customize the layout of our web app. We’ll explore how to set a wide page layout to ensure a visually appealing and user-friendly interface.</p><pre># use whole page width<br>st.set_page_config(page_title=&quot;My Streamlit App&quot;, layout=&quot;wide&quot;)</pre><p><strong>Reading the CSV File</strong></p><p>Before we can begin working with data, we’ll need to read the CSV file that contains our inventory information. We’ll delve into the process of loading this data into our Streamlit app, enabling us to access and manipulate it seamlessly.</p><pre># read csv file<br>df = pd.read_csv(&quot;inventory.csv&quot;)</pre><p><strong>Preparing Checkbox Column</strong></p><p>We want to interact with our data, and one of the crucial interactions is to be able to select each row individually. To be able to do that, we need these checkboxes prepared in each of the rows.</p><pre># preparing empty check boxes for the dataframe<br>df[&quot;selected&quot;] = [False for i in range(df.shape[0])]</pre><p><strong>Product Categories</strong></p><p>To populate our selectbox, we need a list of unique product categories. Use Pandas functions like unique()to extract these categories from the dataframe.</p><pre># preparing sub-category names for the selectbox<br>list_sub_category = df[&quot;sub-category&quot;].sort_values().unique().tolist()</pre><p><strong>Utilizing Streamlit Session State</strong></p><p>If we want our dataframe in streamlit to be changeable after certain action(s), we need to declare it not as a normal dfanymore, but we need to use st.session_state.dfinstead, with dfbeing the name of your dataframe. I defined two dynamic dataframes here, dfand full. We will discuss more about it later in this article, but dfis an empty dataframe with only the column labels, while fullis a complete inventory dataframe that has all the rows and columns.</p><pre># defining dataframe we want to dynamically interact with and <br># make changes to within streamlit session. <br># it is to be declared once at the beginning, like this:<br>if &#39;df&#39; not in st.session_state:<br>        st.session_state.df = pd.DataFrame(columns = df.columns)<br>if &#39;full&#39; not in st.session_state:<br>        st.session_state.full = df.copy()</pre><p>In order to create page columns in streamlit, we will use st.columns and define the size of each column. Notice that the sizes are more of a ratio than an actual size. That means, if your write [3,3,3], the size will be exactly the same as when you write them as [1,1,1].</p><pre>a1,a2,a3 = st.columns([.75,.25,2])</pre><p><strong>First Page Column Components</strong></p><p>In the first page column of our Streamlit application, we’ll design a user-friendly interface for adding items to our inventory. Here are the key components we’ll include:</p><ul><li>selectboxfor Product Category: We’ll add a selectboxthat allows users to choose the category of the product they want to update. This selection will help narrow down the available products.</li><li>selectboxfor Product Name: Another selectboxwill enable users to pick the specific product they want to add to the list. It’s linked to the selected category, ensuring that only relevant product names are displayed.</li><li>Text Input for Quantity: Users can specify the quantity they want to add to the inventory for the selected product.</li><li>“Add to Cart” Button: To finalize the entry, we’ll include an “Add to Cart” button. When clicked, this button will capture the user’s selections and quantity input, adding the item to the prepared dataframe.</li></ul><pre>with a1:<br>    # writing title to give users a lead<br>    st.subheader(&quot;Add item to inventory&quot;)<br>  <br>    # selecting sub-category before scrolling through product names<br>    sub_category = st.selectbox(&quot;Select product category:&quot;, list_sub_category)<br>    <br>    # retrieving list of recorded items in inventory<br>    list_item = df[&quot;product_name&quot;][df[&quot;sub-category&quot;] == sub_category].sort_values().unique().tolist()<br><br>    # to give an option to search items within all category names:<br>    if st.toggle(&quot;Search in all category&quot;):<br>        list_item = df[&quot;product_name&quot;].sort_values().unique().tolist()<br>    <br>    st.write(&quot;Num. of products in this category:&quot;,len(list_item))<br>    st.write(&quot; &quot;)<br>    st.write(&quot; &quot;)<br>    # setting up a variable to save a product name that will be chosen by user during the interaction<br>    name = &quot;&quot;<br>    name = st.selectbox(&quot;Product Name:&quot;, list_item)<br>    <br>    # option to put a new item in the list if the product is not yet recorded in inventory list<br>    not_in_list = st.checkbox(&quot;Item not in the list.&quot;)<br>    if not_in_list:<br>        name = st.text_input(&quot;Product Name:&quot;)<br>        name = name.title()<br>        product_id = st.text_input(&quot;Product ID:&quot;)<br>        category = st.text_input(&quot;Category:&quot;)<br>        sub_category = st.text_input(&quot;Sub-Category:&quot;)<br>    <br>    # setting up variables to fill in other columns for each entry (row)<br>    sel = False<br>    if not_in_list == False:<br>        product_id = df[&quot;product_id&quot;][df[&quot;product_name&quot;] == name].values[0]<br>        category = df[&quot;category&quot;][df[&quot;product_name&quot;] == name].values[0]<br>        sub_category = df[&quot;sub-category&quot;][df[&quot;product_name&quot;] == name].values[0]<br>    quantity = st.text_input(&quot;Quantity:&quot;)<br><br>    # check if the quantity is a number<br>    q_isnumber = False<br>    if quantity != &quot;&quot;:<br>        try:<br>            quantity = float(quantity)<br>            q_isnumber = True<br>        except:<br>            st.error(&quot;Quantity must be a number.&quot;)<br><br>    # preparing a button that records/appends the user input to the list/dataframe<br>    if st.button(&quot;Add to cart&quot;) and q_isnumber == True:<br>        st.session_state.df = st.session_state.df.append({<br>        &quot;selected&quot;:sel, <br>        &quot;product_id&quot;:product_id,<br>        &quot;category&quot;:category,<br>        &quot;sub-category&quot;:sub_category,<br>        &quot;product_name&quot;:name, <br>        &quot;quantity&quot;:quantity<br>        }, ignore_index = True)<br><br>        # pops a small notification on below-right<br>        st.toast(&quot;Added to list.&quot;)</pre><p>When adding an item to the cart in our Streamlit application, it’s crucial to specify which values correspond to each column in the dataframe. This is achieved by creating a dictionary where the column names act as keys, and the variables containing the user inputs serve as their respective values.</p><p>The first column should look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*P-SPYRvrpayHmr1IfCqYKA.gif" /></figure><h4>Part 2 — Displaying Editable DataFrame and Simple Interactions</h4><p>In this section, we will focus on displaying our inventory data in an editable format using st.data_editor. This feature transforms our dataframe into an interactive table similar to Excel, allowing users to edit cell values with ease. Additionally, we will introduce a new &quot;selected&quot; column with checkboxes for row selection and demonstrate how to delete selected rows from the inventory cart. Here&#39;s what we&#39;ll cover:</p><ul><li>Using st.data_editor: We&#39;ll explore how to display and interact with our inventory data using st.data_editor. This tool enables users to edit cell values by clicking on them, offering a seamless Excel-like experience.</li><li>Adding the “selected” Column: We’ll add a new column called “selected” to our inventory cart. This column will contain checkboxes for each row, facilitating the selection of specific items for further actions.</li><li>Creating a “Delete Row” Button: We’ll implement a “Delete Row” button that allows users to remove selected rows from the inventory cart. This functionality streamlines the management of cart items.</li><li>Formatting the Inventory Cart: To enhance user experience, we’ll format the inventory cart as a grouped table. This formatting accommodates scenarios where users add the same product multiple times, ensuring quantities are correctly aggregated.</li></ul><p>Notice that the<strong> Part 1</strong> is written within the page column a1, while this <strong>Part 2</strong> in page column a3. The page column a2is only declared as an empty column to add more space between both columns a1and a3.</p><pre>with a3:<br>    st.subheader(&quot;Items to be added&quot;)<br>    # not sure why session state is declared again here lol<br>    if &#39;df&#39; not in st.session_state:<br>        st.session_state.df = df.copy()<br>    <br>    # toggle button<br>    if st.toggle(&quot;Show data&quot;):<br>        # to display the number of item in the list<br>        st.write(&quot;Num. of entry:&quot;, st.session_state.df.shape[0])<br><br>        # displaying dataframe with st.data_editor<br>        # and applying st.column_config inside data_editor<br>        # 1. creating df.groupby to merge items with identical product name<br>        # 2. adding checkbox inside column_config parameter with False (unchecked) as default value<br>        # 3. hiding dataframe index so it will appear a bit &quot;cleaner&quot; without index column<br>        st.session_state.df = st.data_editor(<br>        st.session_state.df.groupby([&quot;selected&quot;,&quot;product_name&quot;,&quot;category&quot;,&quot;sub-category&quot;,&quot;product_id&quot;]).agg({&quot;quantity&quot;:&quot;sum&quot;}).reset_index(), <br>        column_config = {<br>        &quot;selected&quot;: st.column_config.CheckboxColumn(&quot;selected&quot;, default = False)<br>        }, hide_index = True, use_container_width=True)<br>        <br>        b1,b2,b3 = st.columns([1,1.5,1.5])<br>        with b1:<br>        # setting up button to delete selected rows<br>            if st.button(&quot;Delete selected&quot;):<br>                st.session_state.df = st.session_state.df[st.session_state.df[&quot;selected&quot;] == False]<br>                st.success(&quot;Data deleted.&quot;)<br>        with b2:<br>        # setting up button to empty the cart<br>            if st.button(&quot;Delete all&quot;):<br>                cols = st.session_state.df.columns<br>                st.session_state.df = pd.DataFrame(columns = cols)<br>                st.success(&quot;Data deleted.&quot;)<br>        with b3:<br>        # setting up button to add the quantity to the <br>        # actual quantity of mentioned item in the inventory data.<br>            if st.button(&quot;Save changes to inventory data&quot;):<br>                for i,j in list(zip(st.session_state.df[&quot;product_name&quot;],st.session_state.df[&quot;quantity&quot;])):<br>                    st.session_state.full[&quot;quantity&quot;][st.session_state.full[&quot;product_name&quot;] == i] += j<br>                cols = st.session_state.df.columns<br>                st.session_state.df = pd.DataFrame(columns = cols)<br>                st.success(&quot;Inventory updated. Scroll down to see your inventory data.&quot;)</pre><p>The interaction with the dataframe should look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*8IB6lpbwW4HtxktEy-nWww.gif" /></figure><h4><strong>Last Part — Displaying the Original DataFrame to See the Changes</strong></h4><p>After discussing how to change the dataframe through interactions in Streamlit, it’s essential to verify that our modifications are effective. In the beginning we defined a dataframe called full as a copy of the original inventory data. We will want to display this dataframe. To do this, we’ll create a space to display the original inventory data, allowing us to compare the updated data with the original.</p><ul><li>selectbox for categories: We’ll include a selectboxthat allows users to choose a specific product category. This feature streamlines the process, preventing users from scrolling through thousands of unique items in the inventory.</li><li>Using st.dataframe: To display the original data, we can utilize the familiar st.dataframe function. We should ensure that this display is in a separate section or space within our Streamlit app for user convenience.</li></ul><p>The last code should look like this.</p><pre>st.divider()<br>b1,b2,b3 = st.columns([1,3,1])<br>with b2:<br>    search_sub_category = st.selectbox(&quot;Select category to display:&quot;, list_sub_category)<br>    if st.toggle(&quot;Display data of selected category&quot;):<br>        st.dataframe(st.session_state.full[st.session_state.full[&quot;sub-category&quot;] == search_sub_category])</pre><h4>Wrapping Up</h4><p>Now that we have discussed the code snippets separately to identify which part does which task, we still need to be careful with the code formatting and indentations. It happens quite often when we write a full script of code, that the indentations was not correct, especially when you have lots of stacked for ‘s and if ‘s. For exactly that reason, I decided to paste the code as a whole script so you can copy it, or use it as orientation.</p><pre># importing libraries<br>import pandas as pd<br>import streamlit as st<br><br># use whole page width<br>st.set_page_config(page_title=&quot;My Streamlit App&quot;, layout=&quot;wide&quot;)<br><br># read csv file<br>df = pd.read_csv(&quot;inventory.csv&quot;)<br><br># preparing check boxes for the dataframe<br>df[&quot;selected&quot;] = [False for i in range(df.shape[0])]<br><br>list_sub_category = df[&quot;sub-category&quot;].sort_values().unique().tolist()<br><br># le title<br>st.header(&quot;Inventory Manager&quot;)<br>st.divider()<br><br># defining dataframe we want to dynamically interact with and make changes to within streamlit session. <br># declared once at the beginning, like this:<br>if &#39;df&#39; not in st.session_state:<br>        st.session_state.df = pd.DataFrame(columns = df.columns)<br>if &#39;full&#39; not in st.session_state:<br>        st.session_state.full = df.copy()<br># create page columns<br>a1,a2,a3 = st.columns([.75,.25,2])<br><br># first column&#39;s content<br>with a1:<br>    st.subheader(&quot;Add item to inventory&quot;)<br><br>    # selecting sub-category before scrolling through product names<br>    sub_category = st.selectbox(&quot;Select product category:&quot;, list_sub_category)<br>    # retrieving list of recorded items in inventory<br>    list_item = df[&quot;product_name&quot;][df[&quot;sub-category&quot;] == sub_category].sort_values().unique().tolist()<br><br>    # to give an option to search items within all category names:<br>    if st.toggle(&quot;Search in all category&quot;):<br>        list_item = df[&quot;product_name&quot;].sort_values().unique().tolist()<br>    <br>    st.write(&quot;Num. of products in this category:&quot;,len(list_item))<br>    st.write(&quot; &quot;)<br>    st.write(&quot; &quot;)<br>    # setting up a variable to save a product name that will be chosen by user during the interaction<br>    name = &quot;&quot;<br>    name = st.selectbox(&quot;Product Name:&quot;, list_item)<br>    <br>    # option to put a new item in the list if the product is not yet recorded in inventory list<br>    if st.checkbox(&quot;Item not in the list.&quot;):<br>        name = st.text_input(&quot;Product Name:&quot;)<br>        name = name.title()<br>    <br>    # setting up variables to fill in other columns for each entry (row)<br>    sel = False<br>    product_id = df[&quot;product_id&quot;][df[&quot;product_name&quot;] == name].values[0]<br>    category = df[&quot;category&quot;][df[&quot;product_name&quot;] == name].values[0]<br>    sub_category = df[&quot;sub-category&quot;][df[&quot;product_name&quot;] == name].values[0]<br>    quantity = st.text_input(&quot;Quantity:&quot;)<br><br>    # check if the quantity is a number<br>    q_isnumber = False<br>    if quantity != &quot;&quot;:<br>        try:<br>            quantity = float(quantity)<br>            q_isnumber = True<br>        except:<br>            st.error(&quot;Quantity must be a number.&quot;)<br><br>    # preparing a button that records/appends the user input to the list/dataframe<br>    if st.button(&quot;Add to cart&quot;) and q_isnumber == True:<br>        st.session_state.df = st.session_state.df.append({<br>        &quot;selected&quot;:sel, <br>        &quot;product_id&quot;:product_id,<br>        &quot;category&quot;:category,<br>        &quot;sub-category&quot;:sub_category,<br>        &quot;product_name&quot;:name, <br>        &quot;quantity&quot;:quantity<br>        }, ignore_index = True)<br>        # pops a small notification on below-right<br>        st.toast(&quot;Added to list.&quot;)<br><br>with a3:<br>    st.subheader(&quot;Items to be added&quot;)<br>    # not sure why session state is declared again here lol<br>    if &#39;df&#39; not in st.session_state:<br>        st.session_state.df = df.copy()<br>    <br>    # toggle button<br>    if st.toggle(&quot;Show data&quot;):<br>        # to display the number of item in the list<br>        st.write(&quot;Num. of entry:&quot;, st.session_state.df.shape[0])<br>        st.session_state.df = st.data_editor(st.session_state.df.groupby([&quot;selected&quot;,&quot;product_name&quot;,&quot;category&quot;,&quot;sub-category&quot;,&quot;product_id&quot;]).agg({&quot;quantity&quot;:&quot;sum&quot;}).reset_index(), <br>        column_config = {<br>        &quot;selected&quot;: st.column_config.CheckboxColumn(&quot;selected&quot;, default = False)<br>        }, hide_index = True, use_container_width=True)<br>        b1,b2,b3 = st.columns([1,1.5,1.5])<br>        with b1:<br>            if st.button(&quot;Delete selected&quot;):<br>                st.session_state.df = st.session_state.df[st.session_state.df[&quot;selected&quot;] == False]<br>                st.success(&quot;Data deleted.&quot;)<br>        with b2:<br>            if st.button(&quot;Delete all&quot;):<br>                cols = st.session_state.df.columns<br>                st.session_state.df = pd.DataFrame(columns = cols)<br>                st.success(&quot;Data deleted.&quot;)<br>        with b3:<br>            if st.button(&quot;Save changes to inventory data&quot;):<br>                for i,j in list(zip(st.session_state.df[&quot;product_name&quot;],st.session_state.df[&quot;quantity&quot;])):<br>                    st.session_state.full[&quot;quantity&quot;][st.session_state.full[&quot;product_name&quot;] == i] += j<br>                cols = st.session_state.df.columns<br>                st.session_state.df = pd.DataFrame(columns = cols)<br>                st.success(&quot;Inventory updated. Scroll down to see your inventory data.&quot;)<br><br>st.divider()<br>b1,b2,b3 = st.columns([1,3,1])<br>with b2:<br>    search_sub_category = st.selectbox(&quot;Select category to display:&quot;, list_sub_category)<br>    if st.toggle(&quot;Display data of selected category&quot;):<br>        st.dataframe(st.session_state.full[st.session_state.full[&quot;sub-category&quot;] == search_sub_category])</pre><h4>What’s Next?</h4><p>Due to Streamlit’s deployment on GitHub, making real-time changes to files within the app interface is not straightforward. To update the dataframe, the GitHub repository’s file itself would need to be updated, a process not feasible via Streamlit’s interface.</p><p>A more practical approach, and arguably the most reasonable one, involves linking your data to Snowflake Cloud. When you open the web app, it retrieves data directly from Snowflake rather than relying on the CSV file. This way, you ensure that the latest data is accessible to users. Furthermore, any updates made within the app are reflected in the Snowflake database, allowing for seamless data synchronization and real-time interactions.</p><p>This, however, is going to be a topic for another day. Stay tuned for our upcoming articles on this topic, where we’ll delve deeper into linking your data to Snowflake Cloud for even more powerful data management. In the meantime, keep exploring our coding sessions in Python for various data analytics tasks. Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1147df9d362e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Printing Text Typewriter-Style in Python]]></title>
            <link>https://medium.com/@mdimasaacakradewa/printing-text-typewriter-style-in-python-f51aca968fa8?source=rss-afa8ef4a0dbc------2</link>
            <guid isPermaLink="false">https://medium.com/p/f51aca968fa8</guid>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Muhammad Cakradewa]]></dc:creator>
            <pubDate>Fri, 01 Sep 2023 06:49:04 GMT</pubDate>
            <atom:updated>2023-09-01T07:35:30.784Z</atom:updated>
            <content:encoded><![CDATA[<p>If you print out texts in Python, be it using the <em>print()</em>-command, or <em>display()</em>-command, it will be printed in a matter of few milliseconds. It will be printed out before you finish your first blink. But sometimes you got that feeling when you want to see something else, not for functional purposes, but just for fun. Or you might want to create some videos, where it’s just about texts being printed in a “typewriter”-ish style instead of plain text being displayed instantly. Python happens to be able to create that kind of output, and I find this code snippet interesting to have. I might want to add a moving text in my — lets say — Tableau Dashboard by adding this “typewriter”-ish output in form of a <em>gif, </em>instead just displaying plain text. Or you might want to, I don’t know, just look at the output while taking a break, because some might find it relaxing to look at.</p><p>Here’s the snippet to make that kind of output.</p><pre>import time<br>import sys<br>import random<br><br>def typewriter(text, speed):<br>    delay = []<br>    for i in text:<br>        delay.append(random.randint(1,9))<br>    for char,d in list(zip(text,delay)):<br>        sys.stdout.write(char)<br>        sys.stdout.flush()<br>        time.sleep(d/speed)<br>    display()<br><br># Example usage<br>text_1 =&#39;&#39;&#39;<br>Welcome to our interactive dashboard, where we present <br>a comprehensive view of COVID-19 data across <br>European Union countries from 2020 to 2022. <br>This platform helps you understand the pandemic&#39;s <br>impact through clear visualizations. <br>Dive into a time-series analysis of cases and fatalities, <br>exploring trends and comparisons using easy-to-use filters. <br>Whether you&#39;re curious about a specific country <br>or a particular time frame, this dashboard empowers you <br>to find the answers you seek. <br><br>&#39;&#39;&#39;<br>text_2 = &#39;&#39;&#39;Join us on this journey of insights and exploration <br>as we navigate the data together.&#39;&#39;&#39;<br><br># Printing them out<br>typewriter(text_1,100)<br>typewriter(text_2,60)</pre><p>There. You can just copy paste the snippet and modify it to your will. To modify it, put in your text in a variable, then put inside the parentheses in place of <em>text_1</em> or <em>text_2 </em>there (see the last 2 lines). The number defines how fast you want your text to be printed. The bigger the number, the slower it will be printed. It will give an output like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*l0wIUxT5VZFxy_yFck3xLw.gif" /></figure><p>I copied most of the code from ChatGPT.</p><p>Beautiful, isn’t it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f51aca968fa8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>