<?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 Sri Hartini on Medium]]></title>
        <description><![CDATA[Stories by Sri Hartini on Medium]]></description>
        <link>https://medium.com/@sri.hartini?source=rss-78dbdb6859f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8VCb4v7uD90pqMj5xVEp8A.jpeg</url>
            <title>Stories by Sri Hartini on Medium</title>
            <link>https://medium.com/@sri.hartini?source=rss-78dbdb6859f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 15:47:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sri.hartini/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[Healthcare Cost Prediction Using a Linear Regression]]></title>
            <link>https://medium.com/@sri.hartini/healthcare-cost-prediction-using-a-linear-regression-931a2daeb223?source=rss-78dbdb6859f------2</link>
            <guid isPermaLink="false">https://medium.com/p/931a2daeb223</guid>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[freecodecamp]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Sri Hartini]]></dc:creator>
            <pubDate>Tue, 28 Feb 2023 13:56:42 GMT</pubDate>
            <atom:updated>2023-06-13T22:22:51.790Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-4sIST9N1ql9WcaPE-w_cQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@victoriabcphotographer?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Christina Victoria Craft</a> on <a href="https://unsplash.com/photos/ZHys6xN7sUE?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This article demonstrates the introduction of data analysis before constructing a linear model to forecast healthcare expenses using a dataset with information on diverse people. The information includes costs associated with healthcare as well as factors like age, gender, body mass index (BMI), the number of children, region, and whether or not a person smokes.</p><p>This article, along with my earlier one, is part of my endeavor to complete the <a href="https://www.freecodecamp.org/learn/machine-learning-with-python/machine-learning-with-python-projects/linear-regression-health-costs-calculator">Machine Learning with Python Projects</a> from freeCodeCamp. I have already uploaded my final analysis and model on my Github, which you may check out right away. However, I suggest you keep reading to find out how I came up with the idea.</p><p>Before we begin, keep in mind that in order to pass the challenge, the model must accurately predict health care expenses within $3500. Using test data, determine whether the model’s mean absolute error (MAE) is less than 3500 to verify this.</p><p>Ok, enough with some introduction, let’s get started!</p><h4>Import libraries</h4><p>We will need some module and library to run the code properly, so let’s do it first.</p><pre>import numpy as np<br>import pandas as pd<br><br>import seaborn as sns<br>import matplotlib.pyplot as plt<br><br>import tensorflow as tf<br>from keras import layers, Sequential, optimizers<br><br>plt.style.use(&#39;ggplot&#39;)</pre><p>Just in case you’re wondering what version of tensorflow that I use here. I use Tensorflow 2.9.2. Adding a ggplot style for any plot here wouldn’t hurt, but you can always change it into other styles or not use it at all.</p><h4>Import data</h4><p>We can get the data using code below</p><pre>!wget https://cdn.freecodecamp.org/project-data/health-costs/insurance.csv<br>dataset = pd.read_csv(&#39;insurance.csv&#39;)<br>dataset.tail()</pre><p>and will get the output like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*oe2chArtNZWEzIaNz6BbxQ.png" /></figure><p>Here’s some info related to the dataset. There are seven columns namely age, sex, bmi, children, smoker, region, and expenses. The first six is what you called features. The last column is your true value of expenses for each observation. The sex, smoker, and region are categorical, while the rest have numeric values. To see what values that is in every categorical features, we can use the code below</p><pre># check the unique value for every categorical feature<br>for col in [&#39;sex&#39;, &#39;smoker&#39;, &#39;region&#39;]:<br>    print(dataset[col].unique())</pre><p>and you will then see that sex consists of male and female, smoker consists of yes and no, region consists of southwest, northwest, southeast, and northeast.</p><p>All’s good, and I would like to make another copy of the dataset that I can experimenting on. The dataset that we have here is relatively small. There are 1338 observation and seven columns, so it wouldn’t be problem to make a copy of them. The way to do so is simply using this one line of code.</p><pre># make a copy of dataset<br>df = dataset.copy()</pre><p>Now comes the time I would like to talk about how I handle the data.</p><h4>Garbage in, garbage out</h4><p>At my first time seeing this data, I assume the data has already clean and don’t make any inspection through the data. Or even though it’s not, I think the model will find out its own way to make better prediction. So, I tried to build a model right away following tutorial from Tensorflow <a href="https://www.tensorflow.org/tutorials/keras/regression">here</a> with a little modification on the linear_model using the code below:</p><pre>model = tf.keras.Sequential([<br>    normalizer,<br>    layers.Dense(16),<br>    layers.Dense(units=1)<br>])</pre><p>You can see training process through the graph below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*gNkk0cjTj-LfxhGWFwuslQ.png" /></figure><p>I run it for 100 epoch, but you can tell there is a sign of overfitting there. The model doesn’t work well on predicting new data a.k.a validation data. And if we force to use this model to predict separate test data set, the MAE isn’t satisfied as well. The MAE will be stuck above 4000, with no way to go down no matter how you change the number of units in the dense layer or the number of epochs. And here’s the plot between the test dataset and the constructed linear model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*jHAu_pu6UC77NU0y6kchjA.png" /></figure><p>My first two assumptions that I said earlier are bad practices. Not all of the data is clean when it comes to us, so it’s better to take a look and see if there is something that has to be done before the data is fed into the training process. I know we make a model using TensorFlow, and it sounds so cool, but they still learn from data. Not to mention the model that we need to build is linear regression, which doesn’t add non-linearity into the model that can learn complex patterns from data.</p><p>Unfortunately, I was unaware of this for several hours while working on this project and instead focused on how to normalize numeric values. The reason for doing this is because in the tutorial that I mentioned before, they normalize all the features for simplicity while saying that there is no advantage to normalizing the one-hot features. The good news is that they give <a href="https://www.tensorflow.org/tutorials/structured_data/preprocessing_layers">a link to the other tutorial</a> that explains how to give different treatment to different kinds of features, such as binary, numeric, and categorical features. It’s a good lesson to learn how to give different treatments according to the type of data before feeding it into the model. However, it didn’t make me pass the challenge either. This time, the MAE will be stuck above 3500, not enough to pass the challenge.</p><p>Later on, I would start questioning the data. I assumed that there would be outliers that would disrupt the training process. You know, there’s a saying, “Garbage in, garbage out.” I then used a box plot to find if there were any outliers in every column that had numeric values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*ponTlNkvHIuOAYb7bOX1Jw.png" /></figure><p>No outlier exists on age and children feature, but there are some in bmi and expenses. I started to search a way to remove outliers from data. One of the ways that I found is using interquartile range (IQR). Using this method, any observations that are more than 1,5*IQR below Q1 or more than 1,5*IQR above Q3 are considered outliers. In the other words, the black dots on the right side of each boxplot above are what we called outliers.</p><p>Since there are outliers seen in bmi and expenses, I only remove outliers from those columns. First, I made the function to do that repeatedly.</p><pre>def remove_outliers(data, column_name):<br>    # IQR<br>    Q1 = np.percentile(data[column_name], 25, interpolation=&#39;midpoint&#39;)<br>    Q3 = np.percentile(data[column_name], 75, interpolation=&#39;midpoint&#39;)<br>    IQR = Q3 - Q1<br>    print(&quot;Old Shape: &quot;, data.shape)<br><br>    # Upper bound<br>    upper = np.where(data[column_name] &gt;= (Q3+1.5*IQR))<br>    # Lower bound<br>    lower = np.where(data[column_name] &lt;= (Q1-1.5*IQR))<br><br>    # Remove outliers<br>    data.drop(upper[0], inplace = True)<br>    data.drop(lower[0], inplace = True)<br><br>    data.reset_index(drop=True, inplace = True)<br>    print(&quot;New Shape: &quot;, data.shape)<br>    return data</pre><p>Then I use the function for bmi and expenses columns.</p><pre>df = remove_outliers(df, &#39;bmi&#39;)<br>df = remove_outliers(df, &#39;expenses&#39;)</pre><p>At first, removing outliers from bmi column reduced the number of observations to 1329. The number of observations decreases to 1191 after more outliers are removed from expenses.</p><p>My next move is to peek at every feature and see if there is any obvious correlation between the feature and health expenses. Who knows, I might be able to use just a few features to make better predictions.</p><pre>df.hist(column=&#39;expenses&#39;, by=&#39;sex&#39;, figsize=(8,4), layout=(2,1), sharex=True)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*wDJNufGF473FAaf1yQjRhg.png" /></figure><pre>df.hist(column=&#39;expenses&#39;, by=&#39;smoker&#39;, figsize=(8,4), layout=(2,1), sharex=True)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*xElUGR0S0VFFVmM9mTo7Qw.png" /></figure><pre>df.hist(column=&#39;expenses&#39;, by=&#39;region&#39;, figsize=(8,8), layout=(4,1), sharex=True)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*MV7CeYciOBRufxbcngfthw.png" /></figure><pre>sns.pairplot(<br>    df,<br>    x_vars=[&#39;age&#39;, &#39;bmi&#39;, &#39;children&#39;],<br>    y_vars=[&#39;expenses&#39;],<br>    height=4<br>)<br><br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*HOpgjBlDkT6D74gibAw5eA.png" /></figure><p>My first thought after seeing those graphs was that columns smoker and age could be sufficient features to make better predictions of health-care costs. After I experimented with it, it turned out to be true. The testing set MAE is around 2100 which pretty good compared to the baseline of required MAE to pass the challenge. The training process is also good. No big sign of overfitting even before 20 epoch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*vAw0gsMvjL0_uJU7wctj7g.png" /></figure><p>And here’s the plot between the test dataset and the constructed linear model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*FaSsviU-Y3cdjgw3MJeP2w.png" /></figure><p>It’s far better than the previous one. It’s probably because we omitted outliers from the expenses column too. A similar effect will also be achieved if we choose to use all the features, though. I suspect other features don’t add much additional knowledge to the model, and these two features ended up being the most important in making the decision. I can’t say that’s exactly what happened without showing you the proof, but yeah, that’s my opinion. The result of training and testing if we choose to use all the features might look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*c7m1fbmghtImLjNZ4_tTMQ.png" /></figure><p>I actually intend to guide you through the process from preprocessing the data input to evaluating the model, but I don’t believe it will be very helpful since you can find the same procedure in <a href="https://github.com/hrtnisri2016/fcc-ml-python-projects/blob/main/fcc_predict_health_costs_with_regression.ipynb">my Github</a> as well. The model will give MAE values around 2000.</p><h4>Additional Infos</h4><p>Checking for duplicate rows in the dataset was something I skipped the last time I did this project. There is, if you look carefully. You can also check this by using the code below:</p><pre>dataset[dataset.duplicated(keep=False)]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*N3EvncpMvJtzv78qI26yxA.png" /></figure><p>You can try to delete one of the rows, then re-run the model again. If you’re not sure how, you can do it by using this one-line code.</p><pre>dataset.drop_duplicates(inplace=True)</pre><p>You might be surprised because the MAE value for the testing set will be around 1890. What a further advancement!</p><p>The result of training and testing might look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*CfG7ZjW9PbLkBdwLNX2iLQ.png" /></figure><p>I have to admit that it was fun to work on this project. It is challenging and confusing at the same time. I sometimes think I’ve reached a dead end; other times, I’m just curious about all of the what-if scenarios I can try out and see what happens.</p><p>What if we keep outliers in the BMI column and only remove outliers from the expenses column? Despite MAE being close to 3000, the model will still pass the test. The opposite is also true. Even with MAE values of 3200, the model will still succeed in the test. Only when we don’t address the outliers does the model appear to fail the test.</p><p>What if I try to classify BMI into categories like underweight, normal, overweight, and obese instead of using it as a numerical feature? That’s what I also tried, and it seems to work just fine with the MAE of about 3000.</p><p>There are undoubtedly many more scenarios you could test out on your own, and I’d be delighted if you wanted to share your exciting discovery.</p><p>Thanks for reading!</p><p>I hope you’ll find this article interesting and useful. Consider clapping, following, and subscribing to show your support for my writing. I’ll come back with more projects so we can all learn. See you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=931a2daeb223" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rock Paper Scissors in Python]]></title>
            <link>https://medium.com/@sri.hartini/rock-paper-scissors-in-python-5173ab69ca7a?source=rss-78dbdb6859f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5173ab69ca7a</guid>
            <category><![CDATA[freecodecamp]]></category>
            <category><![CDATA[rock-paper-scissors-game]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Sri Hartini]]></dc:creator>
            <pubDate>Tue, 06 Dec 2022 05:59:40 GMT</pubDate>
            <atom:updated>2023-06-13T22:23:37.490Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M-BxEXxEwFpVRiDi8ujWHw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/es/@imanitor?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Fadilah Im</a> on <a href="https://unsplash.com/s/photos/rock-paper-scissors?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>The Rock Paper Scissors project is one of the projects that must be completed to earn the <a href="https://www.freecodecamp.org/learn/machine-learning-with-python">freeCodeCamp “Machine Learning with Python”</a> certification. In this article, I’ll describe the steps I took to complete this project. You may disagree with me, but I believe that this is the trickiest program I had to create. I took inspiration for my solution from <a href="https://replit.com/@IndraSubagja/boilerplate-rock-paper-scissors#RPS.py">Indra Subagja’s code</a> and <a href="https://letientai.io/freecodecamp/ai/rps/">Tai Le’s post</a>. So please feel free to look it over as well.</p><p>For this challenge, we will create a program to play Rock, Paper, Scissors. A random picker will usually be successful 50% of the time. To succeed in this challenge, our program must compete in games against four different bots while winning at least 60% of the time. Quincy, Abbey, Kris, and Mrugesh are four different bots. They play as follows:</p><ul><li><strong>Quincy</strong> has a five-play pattern that repeats itself: “rock, paper, paper, scissors, rock.”</li></ul><pre>def quincy(prev_play, counter=[0]):<br>    counter[0] += 1<br>    choices = [&quot;R&quot;, &quot;R&quot;, &quot;P&quot;, &quot;P&quot;, &quot;S&quot;]<br>    return choices[counter[0] % len(choices)]</pre><ul><li><strong>Abbey</strong> tries to keep a record of how the opponent played and tries to beat the most likely moves that the opponent may throw at the game.</li></ul><pre>def abbey(prev_opponent_play,<br>    opponent_history=[],<br>    play_order=[{<br>        &quot;RR&quot;: 0,<br>        &quot;RP&quot;: 0,<br>        &quot;RS&quot;: 0,<br>        &quot;PR&quot;: 0,<br>        &quot;PP&quot;: 0,<br>        &quot;PS&quot;: 0,<br>        &quot;SR&quot;: 0,<br>        &quot;SP&quot;: 0,<br>        &quot;SS&quot;: 0<br>    }]):<br><br>    if not prev_opponent_play:<br>        prev_opponent_play = &#39;R&#39;<br>    opponent_history.append(prev_opponent_play)<br><br>    last_two = &quot;&quot;.join(opponent_history[-2:])<br>    if len(last_two) == 2:<br>        play_order[0][last_two] += 1<br><br>    potential_plays = [<br>        prev_opponent_play + &quot;R&quot;,<br>        prev_opponent_play + &quot;P&quot;,<br>        prev_opponent_play + &quot;S&quot;,<br>    ]<br><br>    sub_order = {<br>        k: play_order[0][k]<br>        for k in potential_plays if k in play_order[0]<br>    }<br><br>    prediction = max(sub_order, key=sub_order.get)[-1:]<br><br>    ideal_response = {&#39;P&#39;: &#39;S&#39;, &#39;R&#39;: &#39;P&#39;, &#39;S&#39;: &#39;R&#39;}<br>    return ideal_response[prediction]</pre><ul><li><strong>Kris</strong> attempts to outplay his opponent’s previous move. It assumes that the opponent will throw the same move on the next play.</li></ul><pre>def kris(prev_opponent_play):<br>    if prev_opponent_play == &#39;&#39;:<br>        prev_opponent_play = &quot;R&quot;<br>    ideal_response = {&#39;P&#39;: &#39;S&#39;, &#39;R&#39;: &#39;P&#39;, &#39;S&#39;: &#39;R&#39;}<br>    return ideal_response[prev_opponent_play]</pre><ul><li><strong>Mrugesh</strong> recalls the opponent’s last ten moves and determines which one appears frequently, then attempts to beat that.</li></ul><pre>def mrugesh(prev_opponent_play, opponent_history=[]):<br>    opponent_history.append(prev_opponent_play)<br>    last_ten = opponent_history[-10:]<br>    most_frequent = max(set(last_ten), key=last_ten.count)<br><br>    if most_frequent == &#39;&#39;:<br>        most_frequent = &quot;S&quot;<br><br>    ideal_response = {&#39;P&#39;: &#39;S&#39;, &#39;R&#39;: &#39;P&#39;, &#39;S&#39;: &#39;R&#39;}<br>    return ideal_response[most_frequent]</pre><p>At first, I attempted to have the bots compete with one another. The outcome is interesting. Quincy can’t seem to beat itself, Abbey, or Kris. It has a 0% winning rate. Only when playing against Mrugesh does it have a winning streak, with a 33.72% winning rate. Kris, predictably, cannot beat itself because it is always tied to itself. Mrugesh is better compared to Quincy, but it consistently performs poorly. Meanwhile, Abbey is quite skilled at this game. It is only satisfying when it defeats itself and Mrugesh. Remember that the winning percentage for each match should be at least 60%. The table below contains information on the winning rate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*ZSdzLiQbbStdArwA19JIzw.png" /></figure><p>Then I attempted to modify Abbey’s function. I begin by looking at the opponent’s three moves back instead of two. I even wrote it naively. That is, I only modified the play_order dictionary to include all three possible moves back. And then repeat for four, five, and six moves back. It is pretty inefficient, and I hope you do not follow the same path. It is preferable to write clean code. I just want to do it as soon as possible because I want to see if the winning rate improves as more recorded moves are added, and listing all possible permutations in the dictionary doesn&#39;t seem so bad at the moment.</p><p>Anyway, I stopped after six moves because the winning rate, which had been increasing as more moves were recorded, began to decline after six moves. That’s also because I was doing it so naively that the number of possible permutations started getting huge. This plot provides additional details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*x5w3na6A0BzOjO8-PD5HOA.png" /></figure><p>We can see from the graph that it is harder to beat Abbey than the others. Even though it is difficult to see on the graph, the winning rate was 59.64% when we looked five moves back, which is nearly 60% but not quite there yet. So, recording five moves before making a decision appears promising.</p><p>Furthermore, because we don’t know what our opponent’s first move will be when we play this game, we make assumptions. And, in order to see our opponent’s last five moves before applying the decision rule, we must play alone for the first four moves. We can only guess what our opponent will do for the first few plays, similar to what <a href="https://replit.com/@IndraSubagja/boilerplate-rock-paper-scissors#RPS.py">Indra Subagja</a> or <a href="https://letientai.io/freecodecamp/ai/rps/">Tai Le</a> did. However, after a little experiment with these two variables, the winning rate improvement doesn’t seem so bad to ignore.</p><p>First, consider our winning rate when we make different assumptions about Abbey’s first move and my constant moves for the first four plays in the table below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*qQ6wIxi4eCyZGVGnyossBA.png" /></figure><p>We can see that by assuming Abbey’s first move is scissors, we improve our winning rate. This is fascinating because Abbey’s actual first move was paper. Furthermore, it appears that my consistent plays throughout the first four games had no effect. However, if we change our focus to the winning rate obtained across all four bots, we can see that the constant moves I choose affect my winning rate on Quincy and Mrugesh, as shown in the table below. This isn’t a big deal because we still win more than 60% of the time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*v5bp4NENpLWt0yO6ApFHcw.png" /></figure><p>I wrote some code, but I keep it as a first draft in case you’re curious about how bad my naive code was. Furthermore, when I test this program on Replit, the win rate is not consistent. So, on <a href="https://replit.com/@SriHartini4/fcc-rock-paper-scissors-by-sri?v=1#RPS.py">Replit</a>, we can first try to play it against four bots to see what the winning rate is, and then the program will run the unit test and play against four bots again. Unfortunately, it works perfectly in the first four matches but not in the unit test. Here’s the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c32eadd6cefab04d348c21c5ca7fcfc1/href">https://medium.com/media/c32eadd6cefab04d348c21c5ca7fcfc1/href</a></iframe><p>Well, I could just add a comment tag to the first four plays, and the unit test would still work fine. I would have passed the test, but I decided not to. I wrote a new draft of my code and ran it through <a href="https://replit.com/@SriHartini4/fcc-rock-paper-scissors-by-sri?v=1#RPS.py">Replit</a> to see if it worked on both the first four matches and the unit test, and it did. It still does. The concept remains the same; I simply cleaned up the code. Here’s the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/978aa77917165a3f818cd2e0b6426b32/href">https://medium.com/media/978aa77917165a3f818cd2e0b6426b32/href</a></iframe><p>Now let me walk you through it. We make a function called player that takes the previous opponent move prev_play, saves it on the list of opponent_history, and saves the record of the last five opponent plays in play_order.</p><p>We don’t know how our opponent will play at the start of the game, so prev_play=&quot;&quot;. It&#39;s empty, and we assume the first move is rock, hence &#39;R&#39;. Then we save it in the opponent&#39;s history.</p><pre>if not prev_play:<br>    prev_play = &#39;R&#39;<br><br>opponent_history.append(prev_play)</pre><p>While we want to keep track of the last five moves of our opponents, we should keep playing until we have enough data. So, until then, I decided to assume that the opponent would throw paper, hence &#39;P&#39;.</p><pre>prediction = &#39;P&#39;</pre><p>When we have enough data to work with, meaning that the opponent_history now at least consists of five moves, I start keeping the record on the play_order dictionary. If you go back to see the way I define play_order in the function, you&#39;ll see that I just make it an empty dictionary. Later on, this play_order will be filled with the player&#39;s last five moves.</p><pre>if len(opponent_history) &gt; 4:<br>    last_five = &quot;&quot;.join(opponent_history[-5:])<br>    play_order[last_five] = play_order.get(last_five, 0) + 1</pre><p>Following that, we make a list of every possible play that can be used by the opponent. We do it by seeing the last four moves and trying to guess what the next move is by seeing how frequent those moves are based on what we’ve seen before.</p><pre>potential_plays = [<br>        &quot;&quot;.join([*opponent_history[-4:], v]) <br>        for v in [&#39;R&#39;, &#39;P&#39;, &#39;S&#39;]<br>    ]<br><br>sub_order = {<br>        k: play_order[k]<br>        for k in potential_plays if k in play_order<br>    }</pre><p>However, the sub_order may be still empty because it couldn&#39;t find the potential plays in the play_order, meaning that we&#39;ve never seen the move before. Hence, we check it first before doing the maximum operation. If the sub_order is not empty, then we make the prediction based on the analysis of the moves record that we&#39;ve kept.</p><pre>if sub_order:<br>        prediction = max(sub_order, key=sub_order.get)[-1:]</pre><p>Lastly, we try to beat the prediction of the opponent’s moves by following the rules of the rock-paper-scissors game.</p><pre>ideal_response = {&#39;P&#39;: &#39;S&#39;, &#39;R&#39;: &#39;P&#39;, &#39;S&#39;: &#39;R&#39;}<br><br>return ideal_response[prediction]</pre><p>The result of running this code on <a href="https://replit.com/@SriHartini4/fcc-rock-paper-scissors-by-sri?v=1#RPS.py">Replit</a> is shown in the image below. As we win at least 60% of the games in each match, the test is going smoothly, and I passed the test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*1guTRdFd53i0VRetaOgkDA.png" /></figure><p>I believe there is another possible way to complete this challenge that is beyond my knowledge. Nevertheless, I’m happy with the work I did and the process that I’ve gone through to complete this challenge.</p><p>I hope you’re enjoying the process of figuring out the solution if you’re currently trying to solve this challenge. It took me a while to feel at peace working on this project and eventually publish this article, but I hope you have an easier way.</p><p>Thanks for reading!</p><p>I hope you’ll find this article interesting and useful. Consider clapping, following, and subscribing to show your support for my writing. I’ll come back with more projects so we can all learn. See you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5173ab69ca7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Celestial Bodies Database: Data Preparation (Part 2)]]></title>
            <link>https://medium.com/@sri.hartini/celestial-bodies-database-data-preparation-part-2-ade94344c73c?source=rss-78dbdb6859f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ade94344c73c</guid>
            <category><![CDATA[data-preparation]]></category>
            <category><![CDATA[data-cleaning-with-python]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[freecodecamp]]></category>
            <category><![CDATA[web-scraping]]></category>
            <dc:creator><![CDATA[Sri Hartini]]></dc:creator>
            <pubDate>Fri, 16 Sep 2022 23:10:41 GMT</pubDate>
            <atom:updated>2023-06-13T22:21:19.497Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WJ79BB187uVwhAoNkWjJSQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@nuvaproductions?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Javier Miranda</a> on <a href="https://unsplash.com/s/photos/planet?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In this article, I’ll demonstrate how I prepare a celestial bodies database using PostgreSQL for <a href="https://www.freecodecamp.org/learn/relational-database/build-a-celestial-bodies-database-project/build-a-celestial-bodies-database">this freeCodeCamp project</a>. Please read <strong>Celestial Bodies Database: Data Preparation (Part 1)</strong> if you haven’t already.</p><p><a href="https://medium.com/@sri.hartini/celestial-bodies-database-data-preparation-part-1-23972a94ad70">Celestial Bodies Database: Data Preparation (Part 1)</a></p><p>Now we will continue to create the next table: the planet table.</p><p>Let’s start by looking at a list of the planets’ names that corresponds to the moon table from earlier. Keep in mind that every moon ought to have a foreign key that refers to one of the planet table’s rows. Therefore, we must ensure that the planet table contains this list of planets.</p><pre>must_have_planets = df_moon.planet.unique() <br>print(must_have_planets)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*jIo_gCrvEhEKHabBvm7sEg.png" /></figure><p>Now, let’s use web scraping to obtain the planet table from <a href="https://en.wikipedia.org/wiki/Planet#Solar_System">this website</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a35a9a8867b173a0d93da4cab409d123/href">https://medium.com/media/a35a9a8867b173a0d93da4cab409d123/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1lw28B-32U-0owJ-MZvkKA.png" /></figure><p>There are several columns, but I’ll just use the columns that particularly interest me.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1a9c244be78ae914273ad2d0565a12f/href">https://medium.com/media/b1a9c244be78ae914273ad2d0565a12f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*DN5_AY2OM6vLwkFL15lAww.png" /></figure><p>Now that I feel comfortable with the table, let’s see if it contains every planet on the must_have_planets list. If not, we will have to include the planets&#39; information that is missing from the table.</p><pre>for planet_name in must_have_planets: <br>    if planet_name not in df_planet.name.values: <br>        print(planet_name)</pre><pre>## Output: <br># Salacia <br># Varda</pre><p>You can see from the code above that the data for the planets <a href="https://en.wikipedia.org/wiki/120347_Salacia">Salacia</a> and <a href="https://en.wikipedia.org/wiki/174567_Varda">Varda</a> is not yet included in the table. So, we’ll include it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f88abdf834c49702d2627bf2ad4465bc/href">https://medium.com/media/f88abdf834c49702d2627bf2ad4465bc/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*Kz2h8Mo5xMULLKTN8BZKOA.png" /></figure><p>We can update the planet column in the moon table with the planet_id now that we have completed all the planet names and assigned each one a planet&#39;s id.</p><h4>Creating the first table: moon table (final)</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49179b8376c300d0448a066fb8112bec/href">https://medium.com/media/49179b8376c300d0448a066fb8112bec/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*Lu8wOgFOZSCc0_-dweiEtg.png" /></figure><h4>Creating constellation and star tables</h4><p>Since each planet should have a foreign key that refers to one of the rows in the star table, we might want to start thinking about how to connect the dots between the planet table and the star table.</p><p>The best solution I could come up with is to use a constellation table. The constellation that the planet is “in” could be located. As the planets orbit the sun in a plane, they are much closer to us than the background stars and only appear to move through certain constellations (<a href="http://www.appstate.edu/~goodmanjm/rcoe/elemscience/astronomy/zodiac.html">source</a>), hence the double quotation marks. And when I say background stars, I’m referring to the constellations, which are meaningful star patterns in the sky. The brightest star is also found in each constellation. Therefore, we could add a column to the planet table that indicates the brightest star in the constellation the planet is in.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a092c3c8d54570de12104634bb502af/href">https://medium.com/media/1a092c3c8d54570de12104634bb502af/href</a></iframe><p>[1] The Sky Live, <em>Major Solar System Objects</em>, <a href="https://theskylive.com/planets">https://theskylive.com/planets</a></p><p>[2] The Sky Live, <em>Asteroids</em>, <a href="https://theskylive.com/asteroids-and-dwarf-planets">https://theskylive.com/asteroids-and-dwarf-planets</a></p><p>[3] <em>50000 Quaoar</em>. <a href="https://usuaris.tinet.cat/klunn/quaoar.html">https://usuaris.tinet.cat/klunn/quaoar.html</a></p><p>[4] Wikipedia, <em>225088 Gonggong</em>, <a href="https://en.wikipedia.org/wiki/225088_Gonggong">https://en.wikipedia.org/wiki/225088_Gonggong</a></p><p>Earth, Orcus, and Varda are the three planets for whom I am unable to locate any information on their constellation. However, according to <a href="https://www.space.com/18964-the-nearest-stars-to-earth-infographic.html">this article</a>, the stars closest to Earth are found in the constellation Centaurus, so I’ll put Centaurus in the table as the constellation of Earth. Orcus is also known as Plutino, so I think it probably wouldn’t be wrong to designate Sagittarius as its constellation. In addition, Varda is a binary trans-Neptunian planetoid, thus I give it the same constellation as Neptune, which is Aquarius.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4a5fd0516c8174cd54c8edd7e00d6ec/href">https://medium.com/media/e4a5fd0516c8174cd54c8edd7e00d6ec/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/194/1*eyiIzRWbR1VMV9u4JDzCcA.png" /></figure><p>We can use web scraping again on <a href="https://en.wikipedia.org/wiki/IAU_designated_constellations">this Wikipedia page</a> to obtain the constellation table.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1854c80b1b283a8be8fb4677cc3e6aa/href">https://medium.com/media/c1854c80b1b283a8be8fb4677cc3e6aa/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*IOsM470WmuFzVoORclR-3g.png" /></figure><p>Out of practicality, I would like to alter the star column’s use of Greek letters on their records to our alphabet. And if you check further, the star’s name also contains [8]s, so I’ll omit them as well.</p><pre>df_constellation.star.values</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*sD_QuTcqSiTv1PAQsoJu_g.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/128128b45440bdee23ea61a7f7ef25ee/href">https://medium.com/media/128128b45440bdee23ea61a7f7ef25ee/href</a></iframe><pre>df_constellation.star.values</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*IsLatskk0WAdyMrUjMqt7w.png" /></figure><p>The star names of each planet can now be obtained using the constellation table, and we can then attempt to make the constellation table as simple as possible by omitting the constellation names that we do not use. I decided to approach this project in that manner. You can, however, choose to keep the names of each constellation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/723ceb12d45ba3276940d04b185ae497/href">https://medium.com/media/723ceb12d45ba3276940d04b185ae497/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*CTrYB8bLeM0dPQpSYGzXBA.png" /></figure><pre>keep_constellation = df_planet_constellation.constellation.unique() <br>keep_constellation</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*gVjzUYbkM3MWodTCOBFXvQ.png" /></figure><pre>df_constellation = df_constellation[df_constellation.name.isin(keep_constellation)]</pre><pre>df_constellation = df_constellation.reset_index(drop=True) <br>df_constellation</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*kcs8k8le8cP5gg8F7lg_fQ.png" /></figure><p>Now that we have the constellation table, which includes star names, we can create a star table from it. That would indicate that the stars we will use are Sadalsuud, Hamal, Arcturus, Deneb Algedi, Rigil Kentaurus, Diphda, Beta Comae Berenices, Regulus, Rasalhague, Enif, Kaus Australis, Aldebaran, and Spica.</p><p>If you remember “<a href="https://littleastronomy.com/">Little Astronomy</a>,” there are two links that we can use to construct a star table. Actually, it is made up of many star lists. And while I have made an effort to gather data from the website, doing so would require more work than simply manually gathering the data on each of our desired stars. Therefore, I will create a separate article about the web scraping process used to gather star tables from that website. For the time being, I’ll just create a dictionary that we can later turn into a star table.</p><p>We need also to remember that each star should have a foreign key that references one of the rows in the galaxy table. However, Little Astronomy doesn’t provide information about the galaxy of each star, so I have to look it up on <a href="https://www.universeguide.com/">this website</a>. Don’t forget to include the star_id column as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d31b54096554b9fa067d0a5c37323055/href">https://medium.com/media/d31b54096554b9fa067d0a5c37323055/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*e5cwSUtZWV6kiajnjVsXoQ.png" /></figure><p>We can add a star_id column to the planet table now that we have (almost) completed the star table. Later, we will also replace the galaxy column in this star table with the galaxy_id.</p><h4>Creating the planet table (final)</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6eb61f8ea9791f38785d99502c3b2520/href">https://medium.com/media/6eb61f8ea9791f38785d99502c3b2520/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*FxASh2vLy6IMiP1vyC4Sng.png" /></figure><h4>Creating the constellation table (final)</h4><p>The same procedures can also be applied to the constellation table to replace the star column with each star’s id.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/abdeeef837fb5191f98990e85cb2754e/href">https://medium.com/media/abdeeef837fb5191f98990e85cb2754e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*T-oegWXiPt-VKLkWGL0KxA.png" /></figure><h4>Creating the last table: galaxy table (final)</h4><p>We will now continue to use the same web scraping method as before to create the following table, the galaxy table.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67a34304c1270801edc0f5d3aac2fe51/href">https://medium.com/media/67a34304c1270801edc0f5d3aac2fe51/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*0aP9g0ppFYRxkzCmkC-Pxw.png" /></figure><p>The table contains a total of 37 galaxies. Additionally, it contains a constellation column. Therefore, in order to keep things simple, I only want to keep a few of the names of the galaxies from the table. I will only use the galaxy’s name whose constellation is listed in the previous constellation table in order to accomplish that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/432828f11af0328cd7a9072f4887c929/href">https://medium.com/media/432828f11af0328cd7a9072f4887c929/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*5nlTNCdKeVq0XO1vNZimuQ.png" /></figure><p>I will use the details of galaxies that are visible to the naked eye from <a href="https://en.wikipedia.org/wiki/List_of_galaxies">this website</a> to create one more column. If a galaxy can be seen with the naked eye, it will be set to True; otherwise, it will be set to False. I do this because at least two columns must use the BOOLEAN data type in this database. To meet the requirement, let’s add a column to this galaxy table since we already had one in the planet table.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7885f8019a25ec0bf08ee5f582731514/href">https://medium.com/media/7885f8019a25ec0bf08ee5f582731514/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*snGM9wBRBsY7GFkmk0gCjA.png" /></figure><p>It is now time to add the galaxy’s id and replace the constellation column with its id number.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7648c2cd124535ea87eab8868cb87515/href">https://medium.com/media/7648c2cd124535ea87eab8868cb87515/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*JowagcaodmFcCStSvHGL_Q.png" /></figure><h4>Creating the star table (final)</h4><p>You might also want to go back and check the star table to make sure that each star on our table belongs to the Milky Way galaxy. Its id number is 11, according to the galaxy table. Therefore, we can simply delete the previous galaxy column and add a new column with the id of the Milky Way galaxy.</p><pre>df_star[&#39;galaxy_id&#39;] = [11] * len(df_star) <br>df_star = df_star.drop(columns=&#39;galaxy&#39;) <br>df_star</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*tXC8tPxCJQbeCpY795XOzw.png" /></figure><p>I believe the job is done. Five tables about the moon, planets, stars, galaxies, and constellations are now available. We have complied with all requirements. Below are images of every table we constructed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*IhNtcJKVK6lz4aua4Bk9Qw.png" /><figcaption>moon table (there are actually 50 rows)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*tATlcHeLvwgMJxkfpxiNQQ.png" /><figcaption>planet table</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*ZvpCakLVvK7d7CzUoZNnxQ.png" /><figcaption>star table</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*1Kt2ZuHBKiIXbyAUN6WXpA.png" /><figcaption>galaxy table</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*EU9bn7ZK2LdY4gbNKahpfA.png" /><figcaption>constellation table</figcaption></figure><p>Naturally, we can begin writing SQL commands since the main objective of doing all of this is to compile the table so that we can use PostgreSQL to build a celestial bodies database. However, I won’t write an article about it and will instead keep it on <a href="https://github.com/hrtnisri2016/celestial-bodies-database/blob/f42c9aec6aaedf34c66f26c8c1380ba58cbea155/universe_sql_queries.txt">my GitHub</a>. Therefore, feel free to look it up on <a href="https://github.com/hrtnisri2016/celestial-bodies-database/blob/f42c9aec6aaedf34c66f26c8c1380ba58cbea155/universe_sql_queries.txt">my GitHub</a> if you need any ideas for how to go about doing it.</p><p>Thanks for reading!</p><p>I hope you’ll find this article interesting and useful. Consider clapping, following, and subscribing to show your support for my writing. I’ll come back with more projects so we can all learn. See you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ade94344c73c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Celestial Bodies Database: Data Preparation (Part 1)]]></title>
            <link>https://medium.com/@sri.hartini/celestial-bodies-database-data-preparation-part-1-23972a94ad70?source=rss-78dbdb6859f------2</link>
            <guid isPermaLink="false">https://medium.com/p/23972a94ad70</guid>
            <category><![CDATA[data-preparation]]></category>
            <category><![CDATA[freecodecamp]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[data-cleaning-with-python]]></category>
            <dc:creator><![CDATA[Sri Hartini]]></dc:creator>
            <pubDate>Mon, 12 Sep 2022 00:24:04 GMT</pubDate>
            <atom:updated>2023-06-13T22:29:56.253Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ET9C-cbpomJbaOrMDIYt6Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@bryangoffphoto?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Bryan Goff</a> on <a href="https://unsplash.com/s/photos/galaxy?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>I need to create a celestial bodies database using PostgreSQL for <a href="https://www.freecodecamp.org/learn/relational-database/build-a-celestial-bodies-database-project/build-a-celestial-bodies-database">this freeCodeCamp project</a>. If the term “celestial bodies” is unfamiliar to you, it refers to the planets, stars, moons, and other natural things found in space. And, without a doubt, the first step in creating a database with multiple tables is data preparation.</p><p>In this article, I’ll demonstrate how I prepare data before beginning to write SQL queries. Every piece of information in the tables that I will build has been gathered from the internet, so any corrections to the information provided here are greatly appreciated.</p><h3>Rules for celestial bodies database</h3><p>Let’s look at the guidelines we need to follow for this project in order to build acceptable tables.</p><p>These are the requirements that we must fulfill while creating the tables:</p><ul><li>The database should have <strong>at least 5 tables</strong>.</li><li>There must be a table of the galaxy (≥ 6 rows), star (≥ 6 rows), planet (≥ 12 rows), and moon (≥20 rows).</li><li>Each <strong>table</strong> should have <strong>at least 3 rows</strong> and <strong>3 columns</strong>.</li><li>The galaxy, star, planet, and moon tables should each have at least 5 columns.</li><li>A primary key should be included in each table. The naming standard for primary key columns should be table_name_id. The moon table, for example, should include a primary key column called moon_id.</li><li>Each table should have a name column.</li><li>The <strong>INT</strong> data type must be used in <strong>at least two columns</strong> that are not the primary or foreign keys.</li><li>The <strong>NUMERIC</strong> data type must be used <strong>at least once</strong>.</li><li>The <strong>TEXT</strong> data type must be used <strong>at least once</strong>.</li><li>The <strong>BOOLEAN</strong> data type must be used in <strong>at least two columns</strong>.</li><li>At least 2 columns per table should not accept NULL values.</li><li>At least 1 column from each table should be required to be UNIQUE.</li><li>Each star should have a foreign key that references one of the rows in galaxy.</li><li>Each planet should have a foreign key that references one of the rows in star.</li><li>Each moon should have a foreign key that references one of the rows in planet.</li><li>Each foreign key column should have the same name as the column it is referencing.</li></ul><h3>Finding data sources</h3><p>I was never interested in astronomy before this assignment. I didn’t know much about the names of stars, moons (except our moon), or even the name of the galaxy we live in. I’m sorry. However, I am quite familiar with the names of planets. So, the first question that came to my mind was, “What are things that I can classify as celestial bodies?” There are seven of them, as it turns out: stars, planets, satellites (our moon is Earth’s natural satellite), comets, asteroids, meteors and meteorites, and galaxies.</p><p>So, we can make seven tables about celestial bodies, but let’s keep things simple. You may recall from the rules that I am required to create a table of galaxies, stars, planets, and moons. They are four tables in total, and I require at least five. Let’s start with the four; perhaps there’s a way to figure out what’s needed in the other tables.</p><p>In my search for websites that can provide me with tables, I came across a website called “<a href="https://littleastronomy.com/">Little Astronomy</a>,” which I found to be both interesting and useful. Here are the links I chose to start web scraping with:</p><ul><li><a href="https://littleastronomy.com/galaxy-names/">The Complete List of Galaxy Names</a></li><li><a href="https://littleastronomy.com/list-of-stars-per-constellation/">List of stars per constellation</a></li><li><a href="https://littleastronomy.com/star-names-that-start-with-a/">Star Names That Start With A</a> and there is a page for each letter from A to Z</li><li><a href="https://littleastronomy.com/moon-names/">Moon Names: The Complete List</a></li></ul><p>When you click on the links, you’ll notice that the table of galaxy and star names contains a column called “Constellation,” which describes the constellation in which the galaxy is located or the group of stars to which the star belongs.</p><p>It inspires me to create its own table, the constellation table. However, there isn’t much information about constellations on this website other than their names, so I went to another website, <a href="https://en.wikipedia.org/wiki/IAU_designated_constellations">IAU designated constellations from Wikipedia</a>. Moreover, I find a planet table on this website, <a href="https://en.wikipedia.org/wiki/Planet#Solar_System">Planet from Wikipedia</a>.</p><p>So, that’s all the information I have for now. We can always find additional sources as we work on the tables. Let’s get started on the first table right away.</p><p>We can begin at any table, but I prefer to begin with the moon table. Why? Because the rules state that the moon table should refer to the planet table, which refers to the star table, which refers to the galaxy table. So I believe I can begin with the first table in this chain. That’s what I think, but surely you can start building from any table.</p><h3>Creating the first table: moon table</h3><p>The web scraping codes provided below were inspired by <a href="https://medium.com/analytics-vidhya/web-scraping-a-wikipedia-table-into-a-dataframe-c52617e1f451">this Medium article</a>. I like its simplicity and detailed explanation of the article, so you might want to check it out as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02db5ffedd402a1815734f5d199b2cf4/href">https://medium.com/media/02db5ffedd402a1815734f5d199b2cf4/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*1JH80hJaR2dCrP0Y9suuQw.png" /></figure><p>Hmm, there should be at least five columns, not four (including moon id, which we will add later). Let’s add one more column.</p><p>I find <a href="https://courses.lumenlearning.com/suny-astronomy/chapter/selected-moons-of-the-planets/">this website</a> helpful. It includes many additional columns, but I’ll only include one that I find interesting. I’ll go with “Diameter (km)”, then. Let us now retrieve another table.</p><p>But wait. While I could obtain all of the rows and columns, I only require the Satellite Name and Diameter (km) columns. If you look at the table on the website, you&#39;ll notice that some of the &lt;tr&gt; tags have eight &lt;td&gt; in them, while others only have seven. This is due to the fact that they combine rows in Planet (moons) column for moons from the same planet. So, be careful when writing the codes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*gJuQKb-4bAojC1hBPVJ6Qw.jpeg" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/771fd4be19e0e5f685fc9fbcfa474668/href">https://medium.com/media/771fd4be19e0e5f685fc9fbcfa474668/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*3Bwenz_Gyn1jxzA3gl9BtQ.png" /></figure><p>Now we just need to join those two tables together.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6387a2e4263b2eaa76246b2fa0b736b4/href">https://medium.com/media/6387a2e4263b2eaa76246b2fa0b736b4/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*KUZ4PARNmU2ZnyLnT-xMjw.png" /></figure><p>There are three moons that don’t appear on the df_moon&#39;s table. However, the row with indexes 166 and 167 appears to have a name that is similar which raises suspicions.</p><p>According to the website, Dysnomea is Eris’s moon, MK2 is Makemake’s moon, and Hi’iaka is Haumea’s moon. So, let’s check the moons of these planets from the df_moon table.</p><pre># First, we first check what planets are in the table<br>df_moon.planet.unique()</pre><pre>## Output<br>## array([&#39;Earth&#39;, &#39;Mars&#39;, &#39;Jupiter&#39;, &#39;Saturn&#39;, &#39;Uranus&#39;, &#39;Neptune&#39;, &#39;Orcus&#39;, &#39;Pluto&#39;, &#39;Salacia&#39;, &#39;Haumea&#39;, &#39;Quaoar&#39;, &#39;Varda&#39;, &#39;Gonggong&#39;, &#39;Eris&#39;], dtype=object)</pre><p>Planet Makemake doesn&#39;t exist in the df_moon table in the first place, so let&#39;s add it to the table with a little change in the moon&#39;s name.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0d005bc96a8b9032fbdd7341aa52757/href">https://medium.com/media/b0d005bc96a8b9032fbdd7341aa52757/href</a></iframe><p>We will now find out about the moon of Eris and Haumea that are listed in the df_moon and df_moon_diameter table.</p><pre>df_moon[df_moon[&#39;planet&#39;].isin([&#39;Eris&#39;, &#39;Haumea&#39;])]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*3fltNAEGIi4ZNYJO3Mjyhg.png" /></figure><pre>df_moon_diameter[df_moon_diameter[&#39;name&#39;].isin([&#39;Dysnomea&#39;, &#39;Hi’iaka&#39;])]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*N7GwPTkrYUvmHz2TKUsALg.png" /></figure><p>Since they actually refer to the same moon, we can change Dysnomea to Dysnomia, but what&#39;s wrong with Hi&#39;iaka, the moon of Haumea?</p><pre>print(df_moon.loc[161, &#39;name&#39;]) # Output: Hiʻiaka<br>print(df_moon_diameter.loc[43, &#39;name&#39;]) # Output : Hi’iaka</pre><p>Great. They do differ in one character as well. Let’s give it the same name as it appears in the df_moon table.</p><pre>df_moon_diameter.loc[41, &#39;name&#39;] = &#39;Dysnomia&#39; <br>df_moon_diameter.loc[43, &#39;name&#39;] = &#39;Hiʻiaka&#39;</pre><p>The diameter_in_km column of the moon_outer_join table would now be the only one that has null values.</p><p>If we tried to remove the rows with null values or use an inner join, the same table would be returned to us in this case. I’m fine with having multiple null values in a single column, but I’d rather not have too many of them. Additionally, as shown by the code below, if we use an inner join, we will only end up with 10 names for planets, whereas if we use an outer join, we can have 15 names. I made the decision to keep all of the names of the planets with moons. How can we then maintain the names of 15 planets while minimizing the number of null values?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fea26586504caa18ef15bd27a4f0023/href">https://medium.com/media/7fea26586504caa18ef15bd27a4f0023/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*LPfYarHGVTuHbwYjZopqsA.png" /></figure><p>In my opinion, the names of planets that don’t exist in planet_inner should be kept. Or, to put it another way, we will remove rows with null values if the planet name is not what we want to keep.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd78de1484490f8aaf8aad31ccd59d25/href">https://medium.com/media/dd78de1484490f8aaf8aad31ccd59d25/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*5mich6RBEWAzEWtdMLm6gA.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18d2a3af656dd72da1fb9233ed434f95/href">https://medium.com/media/18d2a3af656dd72da1fb9233ed434f95/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*K30K6Piy3Dq2Qre3-BI9Mw.png" /></figure><p>I think it’s safe now to create the next table, the planet table (<a href="https://medium.com/@sri.hartini/celestial-bodies-database-data-preparation-part-2-ade94344c73c">see Part 2</a>).</p><p>Later, using the planet table we created, we will replace the planet column in the df_moon table with the planet_id.</p><p>But before we move on, consider clapping, following, and subscribing to show your support for my writing. I’ll come back with more projects so we can all learn. See you in Part 2!</p><p><a href="https://medium.com/@sri.hartini/celestial-bodies-database-data-preparation-part-2-ade94344c73c">Celestial Bodies Database: Data Preparation (Part 2)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23972a94ad70" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>