<?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 Nafiz ALTAY on Medium]]></title>
        <description><![CDATA[Stories by Nafiz ALTAY on Medium]]></description>
        <link>https://medium.com/@nfzaltay?source=rss-75bd09b2171------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LNa7kh8u6iy_1k9l7Ym1tQ.jpeg</url>
            <title>Stories by Nafiz ALTAY on Medium</title>
            <link>https://medium.com/@nfzaltay?source=rss-75bd09b2171------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 23:29:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nfzaltay/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[Importance of Recommendation Algorithm with the example of Netflix]]></title>
            <link>https://medium.com/codex/importance-of-recommendation-algorithm-with-the-example-of-netflix-e80041deb6eb?source=rss-75bd09b2171------2</link>
            <guid isPermaLink="false">https://medium.com/p/e80041deb6eb</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[netflix]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Nafiz ALTAY]]></dc:creator>
            <pubDate>Thu, 07 Oct 2021 15:20:47 GMT</pubDate>
            <atom:updated>2021-10-18T10:59:52.080Z</atom:updated>
            <content:encoded><![CDATA[<h3>Importance of Recommendation Systems with the example of Netflix</h3><h4>Everything is a Recommendation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6InGwjhkJy30HPPlu29n8A.jpeg" /></figure><p>In this article, we will gain awareness about the importance of recommendation systems. We will quickly start with Netflix story followed by the incredible recommendation system that goes on in the background. At the end of the article, I will show you how all of this works with Python.</p><p>I will not go into the details of the recommender systems theoretically in order not to extend it too much. I want to talk about this topic in the following articles.</p><h4>Product personalization is <strong>awareness</strong>.</h4><p>All this starts with making sense of the big data held and using it for the right purpose. Services need to want customers to be aware of how companies are adapting to their tastes. This not only promotes trust in the system but encourages members to give feedback that will result in better recommendations.</p><p>Recommender systems are really critical in some industries as they can generate a huge amount of income when they are efficient or also be a way to stand out significantly from competitors. We are talking about a concept that can be integrated into every sector you can think of, such as banking, e-commerce and the retail sector.</p><h4>Let’s start with Netflix story!</h4><p>I think all we know that Netflix was <strong>purely a movie rental service</strong> in 1997. Users ordered movies on the Netflix website and received DVDs in the post. When they were finished with them, they would simply post them back to Netflix in the envelopes provided. Could you imagine at those days how seen as a boon this service?</p><p>Today, Netflix streams movies and has more than<strong> 209 million</strong> paid subscribers in over <strong>190 countries</strong> around the world. It offers a wide range of TV series, documentaries, and feature films across a wide variety of genres and languages, including original productions.</p><p>In 1998, Netflix launches the first DVD rental and sales site, Netflix.com.</p><p>We can easily say that the exciting part starts from here.</p><p>In 2000, A personalized movie recommendation system is introduced, using members’ ratings on past titles to accurately predict future choices.</p><p>The company also launches its “<a href="https://www.netflixprize.com/index.html">Netflix Prize</a>” a machine learning and data mining competition for movie rating prediction in 2006. Netflix sponsored a competition, offering a grand prize of $1,000,000 to the team that could take an offered dataset of over 100 million movie ratings and return recommendations that were 10% more accurate than those offered by the company’s existing recommender system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*_Zhi9MsmWplESiS23-e0DQ.png" /><figcaption>netflixprize.com</figcaption></figure><p>To explore this technical process more closely, you can read Simon Funk’s <a href="https://sifter.org/~simon/journal/20061211.html">blog post</a>, he shared his findings with the research community</p><p><strong>100 million</strong> anonymous movie ratings, using a system that rates films from one to five stars. This was the largest set of such data released to date.</p><p>Netflix’s focus on recommendation algorithms has changed is because Netflix as a whole has changed dramatically in the last few years. Netflix launched an instant streaming service in 2007, one year after the Netflix Prize began.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*hVBqbIeLSfaK6o8JkpFIqQ.png" /></figure><h4>Do you know this too ? Movie images change according to your interests.</h4><p>Let us consider trying to personalize the image Netflix use to depict the movie Good Will Hunting. Here system might personalize this decision based on how much a member prefers different genres and themes. Someone who has watched many romantic movies may be interested in Good Will Hunting if Netflix shows the artwork containing Matt Damon and Minnie Driver, whereas, a member who has watched many comedies might be drawn to the movie if Netflix uses the artwork containing Robin Williams, a well-known comedian.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*fNlIwSHv2KUlvllm" /></figure><h3>Now let’s get to know these movie recommendation methods a little more closely</h3><p>Recommender systems can be classified into 2 types:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7JxFkZwwqRrUVVuc.png" /></figure><p>I will not go deep into these all methods. In my opinion, those recommender methods are very powerful and open to implement many domains. There will be another articles that may have more technical details.</p><p>Collaborative filtering methods have 3 different sub methods like <strong>user-based collaborative</strong>, <strong>item-based collaborative</strong> and<strong> model based collaborative</strong> (Matrix Factorization) filtering.</p><p>Matrix factorization is a class of collaborative filtering algorithms used in recommender systems. This family of methods became widely known during the Netflix prize challenge due to its effectiveness as reported by Simon Funk in his 2006 blog post.</p><p>But today, I will clearly show you the user-based method, which is one of the collaborative filtering methods.</p><p>The idea of ​​collaborative filtering is simple: User group behavior is used to make recommendations to other users. Since the recommendation is based on the preferences of other users it is called collaborative.</p><blockquote><strong>“Users who are similar to you also liked…”</strong></blockquote><p>Products are recommended to the user based on the fact that they were purchased / liked by users who are similar to the observed user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*_fmPwl67pV04KXFODnWZqw.png" /><figcaption>User based collaborative filtering recommender system — Illustrate by thingsolver.com</figcaption></figure><p>Let’s say you watched these movies and your ratings on related movies:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8zqdqQGGBmDx0ffGE31D1g.png" /></figure><p>We will use MovieLens dataset. It contains 20.000.263 ratings and 465.564 tag applications across 27.278 movies. You can find dataset in this <a href="https://www.kaggle.com/grouplens/movielens-20m-dataset">link</a>.</p><p>And now we will try to recommend you new movies related your movies that you watched and your some of ratings on Netflix.</p><p>I will jump into directly system movie recommendations to show you. If you interest with Python code, <a href="https://github.com/nfzaltay/user-based-recommender/blob/main/user-based-recommender.py">here is my work</a>.</p><p><strong>TA-DA !</strong></p><p>These five movies are movie recommends of system that you will see on screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*qJPPmgxhVc0glFTTSI1u5Q.png" /></figure><p>I will be waiting for your comments and likes.</p><p>I wish everyone success in this learning path.</p><p>Here is my <a href="https://www.linkedin.com/in/nafizaltay/">Linkedin</a>, you can always write me for any questions or discussion.</p><p>References:</p><p><a href="http://www.veribilimiokulu.com/"><em>www.veribilimiokulu.com</em></a></p><p><a href="https://gibsonbiddle.medium.com/a-brief-history-of-netflix-personalization-1f2debf010a1"><em>https://gibsonbiddle.medium.com/a-brief-history-of-netflix-personalization-1f2debf010a1</em></a></p><p><a href="https://netflixtechblog.com/netflix-recommendations-beyond-the-5-stars-part-2-d9b96aa399f5">Netflix Recommendations: Beyond the 5 stars (Part 2)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e80041deb6eb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/importance-of-recommendation-algorithm-with-the-example-of-netflix-e80041deb6eb">Importance of Recommendation Algorithm with the example of Netflix</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Identify your valuable customers]]></title>
            <link>https://medium.com/codex/identify-your-valuable-customers-9738472dd36d?source=rss-75bd09b2171------2</link>
            <guid isPermaLink="false">https://medium.com/p/9738472dd36d</guid>
            <category><![CDATA[customer-analysis]]></category>
            <category><![CDATA[rfm]]></category>
            <category><![CDATA[segmentation]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Nafiz ALTAY]]></dc:creator>
            <pubDate>Wed, 22 Sep 2021 01:04:47 GMT</pubDate>
            <atom:updated>2021-09-22T01:04:47.217Z</atom:updated>
            <content:encoded><![CDATA[<h4>How do you carry out your marketing activities towards your current customers?</h4><p>In this article, I will talk about the RFM that can be customized to many different sectors. We will look at the <strong>Python segmentation</strong> with those who are interested.</p><h3><strong>What is RFM? Is that edible?</strong></h3><p>We call RFM comes from the words Recency, Frequency, Monutery. If you say what these words mean, you can examine the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MsbnvqIhiRBUBZ9-vRlciQ.png" /></figure><p>Based on the assigned RFM behavior scores, customers can be grouped into segments and their profitability can be further analyzed.</p><p>The combined score of the three values is the most beneficial for brands in the eCommerce platform as it requires constant monitoring of customer behavior. The insights from the RFM calculation can provide brands with a clearer understanding of frequent shopping paths and understand the customer reaction to new marketing campaigns.</p><p>RFM model has been widely applied in many practical areas, including nonprofits and financial organizations (banking and insurance industries), online industries, telecommunication industries, travel industries, and marketing industries. In addition, the RFM model can be used to segment customers, calculate customer value and customer lifetime value (CLV), observe customer behavior, estimate the response probability for each offer type and evaluate online reviewers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*9eB6VUbrpgKPonz1LGAj0w.png" /><figcaption>RFM Segment Descriptions</figcaption></figure><p>The resulting matrix looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/0*N24LWkHhEuSYugla.png" /><figcaption>RFM Segment Matrix</figcaption></figure><p>The advantage of RFM are that it is easy to implement and can be used for different types of business. It helps craft better marketing campaigns and improves CRM and customer loyalty.</p><p>It is estimated that customers with a high RFM score will return to the brand for more purchases. With special attention to such <strong>‘loyal’, ‘champion’ customers</strong>, the brand can optimize its advertising activities through feedback.</p><p>A customer with a low RFM score indicates a <strong>reluctance to become a loyal customer</strong>. While their responses to advertising campaigns might be insignificant, marketers should turn focus to their recency parameter and figure out what frustrated or did not appeal to such customers. Through RFM scores, brands know exactly which parameter to focus on for every customer.</p><h3>Let’s start some coding!</h3><p>I will use the <a href="https://archive.ics.uci.edu/ml/datasets/Online+Retail">Online Retail dataset</a> available on the UCI Machine Learning Repository.</p><pre># Import libraries<br>import pandas as pd<br>import datetime as dt<br>from pandas.core.common import SettingWithCopyWarning<br>import warnings<br>import matplotlib.pyplot as plt<br><br># Some display settings<br>pd.set_option(&#39;display.max_columns&#39;, None)<br>pd.set_option(&#39;display.max_rows&#39;, None)<br>pd.set_option(&#39;display.float_format&#39;, lambda x: &#39;%.5f&#39; % x)<br>warnings.simplefilter(action=&quot;ignore&quot;, category=SettingWithCopyWarning)</pre><pre># Read the 2010-2011 data in the Online Retail II excel.<br>sales = pd.read_excel(r&quot;data/online_retail_II.xlsx&quot;, sheet_name=&quot;Year 2010-2011&quot;)</pre><p>We need to understand our data with some descriptive statistics.</p><pre>print(<strong>&#39;{:,} rows; {:,} columns&#39;</strong>.format(sales.shape[0], sales.shape[1]))<br>sales.describe()<br>sales.isnull().sum().sort_values(ascending=<strong>False</strong>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/185/1*OKUoF2FtXrv5Rf9Picpt-Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*QluDS1JaYq6vbt5Jg0gHSw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/175/1*JKH9scp_aIT358YVsxAXFw.png" /></figure><p><em>Remove the missing observations from the data set. Use the ‘inplace=True’ parameter for subtraction.</em></p><pre>sales.dropna(axis=0, inplace=<strong>True</strong>)</pre><p>How many of each product are there?</p><pre>sales[<strong>&quot;Description&quot;</strong>].value_counts().sort_values(ascending=<strong>False</strong>).head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*k_LLrYCNlq9iTHwWoUZ1Kw.png" /></figure><pre><em># The &#39;C&#39; in the invoices shows the canceled transactions. Remove the canceled transactions from the dataset.<br></em>df = sales[~sales[<strong>&quot;Invoice&quot;</strong>].str.contains(<strong>&quot;C&quot;</strong>, na=<strong>False</strong>)]<br><br><em># Create a variable named &#39;TotalPrice&#39; that represents the total earnings per invoice.<br></em>df[<strong>&quot;TotalPrice&quot;</strong>] = df[<strong>&quot;Price&quot;</strong>] * df[<strong>&quot;Quantity&quot;</strong>]<br>df.dropna(axis=0, inplace=<strong>True</strong>)</pre><p>We continue to calculate the <strong>RFM metrics</strong>. We need to define today_date as an analysis date for calculating recency.</p><pre>df[<strong>&quot;InvoiceDate&quot;</strong>].max()<br><em># Timestamp(&#39;2011-12-09 12:50:00&#39;)</em></pre><pre>today_date = dt.datetime(2011, 12, 11)</pre><pre>rfm = df.groupby(<strong>&#39;Customer ID&#39;</strong>).agg({<strong>&#39;InvoiceDate&#39;</strong>: <strong>lambda </strong>invoicedate: (today_date - invoicedate.max()).days,<br>                                     <strong>&#39;Invoice&#39;</strong>: <strong>lambda </strong>invoice: invoice.nunique(),<br>                                     <strong>&#39;TotalPrice&#39;</strong>: <strong>lambda </strong>totalprice: totalprice.sum()})<br><br>rfm.columns = [<strong>&quot;recency&quot;</strong>, <strong>&quot;frequency&quot;</strong>, <strong>&quot;monetary&quot;</strong>]<br>rfm = rfm[(rfm[<strong>&#39;monetary&#39;</strong>] &gt; 0)]<br>print(rfm.describe().T)</pre><p>Calculation of RFM Scores and turning into one variable</p><pre>rfm[<strong>&quot;recency_score&quot;</strong>] = pd.qcut(rfm[<strong>&quot;recency&quot;</strong>], 5, labels=[5, 4, 3, 2, 1])<br>rfm[<strong>&quot;frequency_score&quot;</strong>] = pd.qcut(rfm[<strong>&#39;frequency&#39;</strong>].rank(method=<strong>&quot;first&quot;</strong>), 5, labels=[1, 2, 3, 4, 5])<br><em># We did not consider manutery in this problem due to the correlation relationship with frequency.<br></em>rfm[<strong>&quot;RFM_SCORE&quot;</strong>] = (rfm[<strong>&#39;recency_score&#39;</strong>].astype(str) + rfm[<strong>&#39;frequency_score&#39;</strong>].astype(str))</pre><p><strong>Now it’s time to define!</strong></p><p>The RFM scores give us 53 = 125 segments. Which is not easy to work with. We are going to work with 10 segments based on the R and F scores. We have set up regular expression(regex) structure by using dictionaries to name customer segments according to their Recency and Frequency Scores.</p><pre>seg_map = {<br>    <strong>r&#39;[1-2][1-2]&#39;</strong>: <strong>&#39;hibernating&#39;</strong>,<br>    <strong>r&#39;[1-2][3-4]&#39;</strong>: <strong>&#39;at_Risk&#39;</strong>,<br>    <strong>r&#39;[1-2]5&#39;</strong>: <strong>&#39;cant_loose&#39;</strong>,<br>    <strong>r&#39;3[1-2]&#39;</strong>: <strong>&#39;about_to_sleep&#39;</strong>,<br>    <strong>r&#39;33&#39;</strong>: <strong>&#39;need_attention&#39;</strong>,<br>    <strong>r&#39;[3-4][4-5]&#39;</strong>: <strong>&#39;loyal_customers&#39;</strong>,<br>    <strong>r&#39;41&#39;</strong>: <strong>&#39;promising&#39;</strong>,<br>    <strong>r&#39;51&#39;</strong>: <strong>&#39;new_customers&#39;</strong>,<br>    <strong>r&#39;[4-5][2-3]&#39;</strong>: <strong>&#39;potential_loyalists&#39;</strong>,<br>    <strong>r&#39;5[4-5]&#39;</strong>: <strong>&#39;champions&#39;<br></strong>}</pre><pre>rfm[<strong>&#39;segment&#39;</strong>] = rfm[<strong>&#39;RFM_SCORE&#39;</strong>].replace(seg_map, regex=<strong>True</strong>)<br>rfm.reset_index(inplace=<strong>True</strong>)<br>print(rfm.head())<br>rfm.to_excel(<strong>&quot;rfm_segments.xlsx&quot;</strong></pre><p>We visualize our output data with Tableau.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*U892qx5ziHCpANgHYtxdaA.png" /></figure><p><strong>Congrats!</strong> You’re all set!</p><pre>rfm[[<strong>&quot;segment&quot;</strong>, <strong>&quot;recency&quot;</strong>, <strong>&quot;frequency&quot;</strong>]].groupby(<strong>&quot;segment&quot;</strong>).agg([<strong>&quot;mean&quot;</strong>, <strong>&quot;count&quot;</strong>])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*Z5KrcGV4ESiFzuOxYsfU1Q.png" /></figure><p>In general, the frequency values are quite low. At this point, it may be advisable to organize promotions and high discount campaigns. We need to give our priority to our customers who are present but whose loyalty may decrease day by day.<br><br><strong>It is seen that customers with the cant_loose segment have a high-frequency value</strong> <strong>in the general average</strong>, but they have recently withdrawn from the system themselves. This segment has high earning potential if the right strategies are applied for the company. A significant discount is recommended for quick recovery. A recovery campaign that appeals to emotion can be created.</p><p><strong>The at_Risk segment includes our customers who are familiar with the system and have a significant shopping experience. </strong>It should be in the first place in the segments that need to be focused on, its recovery will provide high returns to the company. Here, promotional campaigns can be organized for the product groups they have shopped for the target audience. There may be a mass that withdraws itself from the system by purchasing a stocked product. Product-based campaigns can be recommended for them.</p><p>Let me know if I missed any steps, if something didn’t work out quite right for you, or if this guide was helpful! Thank you for reading!</p><p><strong>Github:</strong> <a href="https://github.com/nfzaltay/customer-segmentation-rfm">https://github.com/nfzaltay/customer-segmentation-rfm</a></p><p><strong>References:</strong></p><ul><li>Data Science School (Veri Bilimi Okulu)</li><li>Jo-Ting Wei, Shih-Yen Lin and Hsin-Hung Wu, 2010, A review of the application of RFM model, <em>African Journal of Business Management, </em>Vol. 4(19), pp. 4199–4206</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9738472dd36d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/identify-your-valuable-customers-9738472dd36d">Identify your valuable customers</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting started Python with Rule Based Classification Problem]]></title>
            <link>https://medium.com/@nfzaltay/getting-started-python-with-rule-based-classification-problem-6088c0e405d4?source=rss-75bd09b2171------2</link>
            <guid isPermaLink="false">https://medium.com/p/6088c0e405d4</guid>
            <category><![CDATA[mobile-expenses]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[customer-segmentation]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[rule-based]]></category>
            <dc:creator><![CDATA[Nafiz ALTAY]]></dc:creator>
            <pubDate>Thu, 16 Sep 2021 12:18:18 GMT</pubDate>
            <atom:updated>2021-09-16T12:19:37.376Z</atom:updated>
            <content:encoded><![CDATA[<h4>Potential Customer Expends on Mobile Games</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*MT94z8GcS4BvmqJx3ZZN-g.jpeg" /><figcaption>Source: https://www.moneysavingexpert.com/</figcaption></figure><p>Hi everyone, at the end of this article you will discover the awareness of Python data structures and the ease of operations on tables as needed with the project of <strong><em>Calculating Lead-Based Expends with Rule-Based Classification</em></strong></p><p>Data Science, which has become very popular in recent years. It is a matter of curiosity by both companies and individuals. There are many people who want to make a place for themselves in this field where a new job opportunity arises every day. In this learning process, the biggest obstacle to becoming a Data Scientist, which involves multiple disciplines such as mathematics and statistics, may seem to be coding.</p><p>Machine learning and deep learning models that come directly to mind when saying Data Science but may not be necessary in many cases. The real world has a great lack of making sense of the data before these. Your first priority is to stay motivated by playing and exploring with data.</p><p>I will proceed by thinking that you have touched Python or any programming language at some point in your lives. In this article, which does not need technical detailed information, you will observe how Python is used within a very simple project.</p><p>Now, I will share with you the functions and some methods that you will take the first step towards as a data scientist. We will do all this within a project.</p><p>Before starting, we will analyze the case of <strong>Calculating Lead-Based Returns with Rule-Based Classification.</strong></p><p>To summarize our project, one of game company would like to learn how much money its new customers will potentially spend by observing the purchasing movements within the application. The company wants to segment its customers and plan the necessary notifications, additional scores or mail marketing. They assign a Data Scientist for all this and assign this task to him. We will consider this case under basic conditions which should be examined and analyzed in detail.</p><p>You have a dataset that includes the Country, Source, Age, Sex information of the customers and their game purchases.</p><p><strong>You can get persona.csv data from this </strong><a href="https://github.com/nfzaltay/rules-based-classification"><strong>repo</strong></a><strong>.</strong></p><p>We can receive our data, which we will analyze on Python, in formats such as .csv or .xlsx.</p><p><strong>Here is our variables:</strong></p><ol><li>Price: Payments made by costumers</li><li>Source: The operating system used, including IOS and Android</li><li>Sex: Gender of users, Female and Male</li><li>Country : Information from which country the costumers are from</li><li>Age: Age of costumers</li></ol><p>Before moving on to coding, it is useful to get an idea about the Numpy and Pandas libraries. Since this article will contain a simple project-oriented Python explanation, I do not need to go into too much detail. It is only useful to know that the term library is “ a collection of files (called modules) that contains functions for use by other programs”.</p><p>There will be many libraries that we will need as data scientists. Among them, we will only use Pandas for now.</p><blockquote><strong>pandas</strong> is a fast, powerful, flexible and easy to use open source data analysis and manipulation tool</blockquote><p>Getting started, we define our previously downloaded persona.csv dataset as a DataFrame with Pandas’ read_csv function.</p><pre># Using import to load a library module into a program’s memory.<br>import pandas as pd</pre><pre># Reading persona.csv as pandas DataFrame<br>df = pd.read_csv(r&quot;/data/persona.csv&quot;)</pre><p>We want to observe and summarize our dataset with a set of pandas functions. It’s important to really take your time here and understand what these numbers are saying.</p><pre># Analyze descriptive statistics</pre><pre>df.head() # Returns the first 5 rows for quickly checking data<br>df.shape  # Returns a dimensionality of the DataFrame<br>df.describe().T # Generates descriptive statistic<br>df.isnull().values.any() # Returns any value is missing in DataFrame<br>df.isnull().sum() #  Returns how many missing values exist in the DataFrame</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*4q3NP5h_0eajmT8A7mYuhw.png" /><figcaption>Returns the first 5 rows for quickly checking data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*qFrAhsDwIzq8vhvbxwOSKw.png" /><figcaption>Generates descriptive statistic</figcaption></figure><p>Now we look at the unique value numbers and frequencies for a number of categorical variables. We make such operations and observations in order to get to know our data set better.</p><pre># Number of unique &lt;SOURCE&gt;<br>df[&quot;SOURCE&quot;].nunique() # Count number of distinct SOURCE elements<br>df[&quot;SOURCE&quot;].value_counts()# Returns counts of SOURCE rows <br>df[&quot;COUNTRY&quot;].value_counts() # Returns counts of COUNTRY rows</pre><p>Next, we will examine the values of multiple variables together and observe their breakdown. In this code block we will use groupby and aggregation functions. This is perfectly normal if you are not familiar with the functions I have mentioned. It will not be possible for me to describe it here except to describe it with a few sentences. Through these <a href="https://pandas.pydata.org/docs/index.html">documents</a>, you can learn the Pandas function you want with detailed examples.</p><p><strong><em>A</em></strong><em> </em><strong><em>groupby operation</em></strong><em> involves some </em><strong><em>combination of splitting the object</em></strong><em>, applying a function, and combining the results. This can be used to group large amounts of data and compute operations on these groups.</em></p><p><strong><em>Aggregate(agg)</em></strong><em> using one or more operations over the specified axis. Here is the operations : mean, median, prod, sum, std, var</em></p><pre># Country breakdown of income averages<br><br>df.groupby(&quot;COUNTRY&quot;)[&quot;PRICE&quot;].agg({&quot;mean&quot;})<br><br># Country and Source breakdown of income averages<br><br>df.groupby([&quot;COUNTRY&quot;, &#39;SOURCE&#39;])[&quot;PRICE&quot;].mean()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*V8kBBv0RPp1GjUDdLKRgTA.png" /><figcaption>Country breakdown of income averages</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*_FawsCw7Nw9oHxpEMHsI_A.png" /><figcaption>Country and Source breakdown of income averages</figcaption></figure><p>Data analysis can be performed in many different ways with the method we have given above. Now, by grouping many variables in our data, we take the average gains within the combinations into our table in a DataFrame type named agg_df. We sort from largest to smallest by adding the sort_values method to the end of our code.</p><pre># Average income on the basis of variables,<br><br>agg_df = df.groupby([&quot;COUNTRY&quot;, &#39;SOURCE&#39;, &quot;SEX&quot;, &quot;AGE&quot;])[&quot;PRICE&quot;].mean().sort_values(ascending=<em>False</em>)<br>agg_df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*Es0tz-nTbMupmKWGf1KlkQ.png" /></figure><p>After the above processes, all our columns that we received groupby gained index feature in DataFrame. Index is like an address, that’s how any data point across the dataframe can be accessed. Rows and columns both have indexes, rows indices are called as index and for columns its general column names. First, we want to get the index property of these columns and qualify it as a variable.</p><pre># Convert the index names to variable names<br><br>agg_df = agg_df.reset_index() # If False, return a copy. Otherwise, do operation inplace and return None.<br>agg_df.head() # Lets look at new index numbers</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*pX4jXaO38Jv3zyZNPCTpFQ.png" /><figcaption>Converted the index names to variable names</figcaption></figure><p>We want to divide the customers into certain groups by converting the numerical variable of age into a categorical variable. This process is critical for segmenting our customers.</p><p>We defined the ranges of AGE values as string values in the list with the name my_labels.</p><pre># Convert AGE variable to categorical variable and adding it to agg_df<br><br>my_labels = [&#39;0_18&#39;, &#39;19_23&#39;, &#39;24_30&#39;, &#39;31_40&#39;, &#39;41_70&#39;]<br>agg_df[&quot;AGE_CUT&quot;] = pd.cut(x=agg_df[&quot;AGE&quot;], bins=[0, 18, 23, 30, 40, 70], labels=my_labels)<br>agg_df.tail(10) # Just checking data</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*S4VpnHu_40g4XO-sU6Hfnw.png" /><figcaption>Convert AGE variable to categorical variable and adding it to agg_df</figcaption></figure><p>Use cut when you need to segment and sort data values into bins. This function is also useful for going from a continuous variable to a categorical variable. Cut could convert ages to groups of age ranges.</p><p>Next, before we segment our customers, we put them in a persona. Here, I recommend you to research the f-string structure and gain the habit of using it. In the code below, there is a list comprehension structure that saves our lives most of the time. List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list. If you don’t prefer to use list comprehension, you will have to write a for statement.</p><pre># Identify new level-based customers (Personas)<br>agg_df[&quot;customers_level_based&quot;] = [f&quot;{i[0]}_{i[1]}_{i[2]}_{i[-1]}&quot; <em>for </em>i <em>in </em>agg_df.values]</pre><p>Another concept that we need to understand well is the loc method. You can acccess a group of rows and columns by label(s) or a boolean array by loc. It also has a brother, iloc that advances as integer based. loc proceeds as label based. I think you can understand very well from the source <a href="https://towardsdatascience.com/how-to-use-loc-and-iloc-for-selecting-data-in-pandas-bd09cb4c3d79">here</a>.</p><p>The code below should not be confusing to you. In this method, which shows a very simple usage, we use loc function to select all the rows<em> (:) </em>and the columns we want <em>([“customers_level_based”, “PRICE”])</em> from the DataFrame named agg_df. As we have seen use before by grouping it with the groupby and aggregation functions that we separate from the largest to the smallest according to the average returns.</p><pre>agg_df = agg_df.loc[:, [&quot;customers_level_based&quot;, &quot;PRICE&quot;]].groupby(&quot;customers_level_based&quot;).agg({&quot;PRICE&quot;: &quot;mean&quot;}).sort_values(by=&quot;PRICE&quot;, ascending=<em>False</em>).reset_index()</pre><pre>agg_df[&quot;customers_level_based&quot;].head() # Just checking data again</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*bqGU4J2atoUiLTXBph8wRQ.png" /><figcaption><em>Identify new level-based customers</em></figcaption></figure><p>Now we assign the characters of the customers which we have converted to unique values(persona value). We divide the personas into 4 groups from the least profitable customer group to the most profitable customer group. “D, C, B, A”</p><p>This time we separate this separation process into quantiles with qcut, not with cut.</p><p><em>qcut : Quantile-based discretization function</em></p><pre># Segment new customers (Personas)<br><br>agg_df[&quot;SEGMENT&quot;] = pd.qcut(agg_df[&quot;PRICE&quot;], 4, labels=[&quot;D&quot;, &quot;C&quot;, &quot;B&quot;, &quot;A&quot;])<br>agg_df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*ln57-UWvbFvkORBTyhFtxA.png" /><figcaption>Segment new customers (Personas)</figcaption></figure><p>We would like to take a look at the basic statistical values of the customer personas we have segmented. In the last line, there is an example of selecting and describing only the C segment.</p><p>Additional note: These examples and usage patterns may be redundant during ongoing code. It is worth reminding again that the purpose here is to show how to select data from a dataset and to perform basic analysis for this.</p><pre># Describe the segments and especially &quot;C&quot;<br><br>agg_df.groupby([&quot;SEGMENT&quot;]).agg({&quot;PRICE&quot;: [&quot;mean&quot;, &quot;max&quot;, &quot;sum&quot;]})<br><br>agg_df[agg_df[&quot;SEGMENT&quot;] == &quot;C&quot;].describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*5VUb37YnkZY_gvZ2Vq6SFg.png" /><figcaption>Describe the segments</figcaption></figure><p>Now our segmentation process is complete.</p><p>Next is to know which segments the new customers belong to and to potential purchases on average.</p><p>Let’s say a 25-year-old French man downloaded the game and processing on game market with his Android device. In this case, which segment does it belong to and how much does it earn on average?</p><pre>new_user = &quot;fra_android_male_24_30&quot;<br>print(agg_df[agg_df[&quot;customers_level_based&quot;] == new_user])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*agw176X2AnBHlkKJTV0wyA.png" /></figure><p><strong>This customer is in the C segment and spend potentially 33 units of money to the game.</strong></p><p>In this way, special marketing strategies can be planned by segmenting all new customers.</p><p>I will be waiting for your comments and likes.</p><p>I wish everyone success in this learning path.</p><p>Thanks especially going to <strong>VBO (Veri Bilimi Okulu)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*Cm6a4wh5lZPM7kRO54zgrA.jpeg" /></figure><p>References:</p><ul><li><a href="https://librarycarpentry.org/lc-python-intro/06-libraries/index.html">Libraries</a></li><li><a href="https://pandas.pydata.org/docs/index.html">pandas documentation - pandas 2.3.3 documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6088c0e405d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>