<?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 Nesrin ÖZCAN on Medium]]></title>
        <description><![CDATA[Stories by Nesrin ÖZCAN on Medium]]></description>
        <link>https://medium.com/@nesrinozcan?source=rss-c19af14c0bc2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*mew50YfIpx59oPub</url>
            <title>Stories by Nesrin ÖZCAN on Medium</title>
            <link>https://medium.com/@nesrinozcan?source=rss-c19af14c0bc2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 19:51:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nesrinozcan/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[Customer Lifetime Value(CLTV) Prediction Using BG/NBD and Gamma Gamma Models in Python]]></title>
            <link>https://medium.com/akkimakademi/customer-lifetime-value-cltv-prediction-using-bg-nbd-and-gamma-gamma-models-in-python-c98629710f39?source=rss-c19af14c0bc2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c98629710f39</guid>
            <dc:creator><![CDATA[Nesrin ÖZCAN]]></dc:creator>
            <pubDate>Wed, 28 Dec 2022 07:11:56 GMT</pubDate>
            <atom:updated>2022-12-30T11:06:13.611Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RCMzZWKbhhj9u1wYrYrLmQ.jpeg" /></figure><p>Customer Lifetime Value(CLTV) is an important metric in marketing. CLV is the predicted total amount of money a customer is expected to spend on your products. It gives your company a sensible view of the financial value provided by your customers. CLTV can be used as a KPI and as a loyalty measure. CLTV can be calculated based on the existing situation of your customers. You can also predict CLTV for the selected time periods in the future. For CLTV prediction, either statistical models or deep learning models can be used. I will use statistical models like BG/NBD and Gamma Gamma in this project. As a main package I will be using Python-lifetimes package. Firstly I will upload the necessary libraries and then read the data.csv file. You can reach the Kaggle dataset <a href="https://www.kaggle.com/datasets/carrie1/ecommerce-data?datasetId=1985&amp;sortBy=voteCount">here</a>.</p><pre>import datetime as dt<br>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>from lifetimes import BetaGeoFitter<br>from lifetimes import GammaGammaFitter<br>from lifetimes.plotting import plot_period_transactions<br>from lifetimes.utils import summary_data_from_transaction_data<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.width&#39;, 500)<br>pd.set_option(&#39;display.float_format&#39;, lambda x: &#39;%.2f&#39; % x)<br>import seaborn as sns</pre><h3>Data Preprocessing</h3><p>When I look at null values, Description and CustomerID features has many. I will not use the Description feature so it is not important. But I will calculate CLTV specific to CustomerIDs so null values in this feature are meaningless. I will drop the null rows from the dataset.</p><p>Invoice Date feature has object data type, so I will change it to datetime. Amount and Price values also have to be positive values.</p><pre>df = pd.read_csv(&#39;data.csv&#39;, encoding= &#39;unicode_escape&#39;)<br>df.columns = [&quot;INVOICE_ID&quot;, &quot;STOCK_ID&quot;, &quot;DESCRIPTION&quot;,&quot;AMOUNT&quot;, &quot;INVOICE_DATE&quot;,&quot;PRICE&quot;,&quot;COMPANY_ID&quot;,&quot;COUNTRY&quot;]<br>df =df[[&quot;INVOICE_ID&quot;, &quot;STOCK_ID&quot;,&quot;AMOUNT&quot;, &quot;INVOICE_DATE&quot;,&quot;PRICE&quot;,&quot;COMPANY_ID&quot;]]<br>df.dropna(inplace=True)<br>df[&quot;INVOICE_DATE&quot;] = pd.to_datetime(df[&quot;INVOICE_DATE&quot;])<br>df = df[(df[&quot;AMOUNT&quot;] &gt; 0) &amp; (df[&quot;PRICE&quot;]&gt;0)]</pre><p>The dataset has Price and Amount numeric features. I will take a look at outliers in these features with histogram graph.</p><pre>sns.boxplot(df[&quot;PRICE&quot;], orient=&quot;h&quot;,notch=True, showcaps=False)<br>sns.boxplot(df[&quot;AMOUNT&quot;], orient=&quot;h&quot;,notch=True, showcaps=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*dR14yZKp1qy72vaBIIQWQw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*747bf_NkrfHbrGRPmr2T6g.png" /></figure><p>To get more meaningful boxplot graphs, we have to get rid of outliers. Dealing with outliers is a necessary process for data analysis. Outliers, whether they are too big or too small compared to expected values, have big impact on statistical values like mean and standard deviation. Thus for better prediction and analysis, we have to examine outlier values. There are a few ways to deal with outliers, but for this project I will replace outliers with threshold values that are evaluated in (0.05–0.95) range quantiles. I will hold down outlier values and replace them with their threshold values.</p><pre>def outlier_thresholds(dataframe, variable):<br>    quartile1 = dataframe[variable].quantile(0.05)<br>    quartile3 = dataframe[variable].quantile(0.95)<br>    interquantile_range = quartile3 - quartile1<br>    up_limit = quartile3 + 1.5 * interquantile_range<br>    low_limit = quartile1 - 1.5 * interquantile_range<br>    return low_limit, up_limit<br><br>def replace_with_thresholds(dataframe, variable):<br>    low_limit, up_limit = outlier_thresholds(dataframe, variable)<br>    dataframe.loc[(dataframe[variable] &gt; up_limit), variable] = up_limit<br>replace_with_thresholds(df, &quot;AMOUNT&quot;)<br>replace_with_thresholds(df, &quot;PRICE&quot;)</pre><p>After replacing outliers with threshold values, let’s look at the boxplots again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*D-i-FFxqOp2n5yXJIKDT3g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*-6KNUOdvUtgJ379QTeNPKw.png" /></figure><p>Now the data distributions for Price and Amount features make more sense for our CLTV project.</p><p>I need an ending date for CLTV calculation. I will find the max date in my dataset, add 2 days to this date and will use it as the ending date in calculation. We need Total Price feature to be able to calculate cltv.</p><pre>from datetime import timedelta<br>df[&quot;TOTAL_PRICE&quot;] = df[&quot;AMOUNT&quot;] * df[&quot;PRICE&quot;]<br>today_date= df.INVOICE_DATE.max() + timedelta(days=2)<br>today_date<br><br>Output : Timestamp(&#39;2011-12-09 12:50:00&#39;)</pre><h3><strong>Frequency, Recency, Tenure and Monetary values</strong></h3><p>We need frequency, recency, tenure and monetary values for further calculations. We can calculate these values in a few steps but lifetimes library has already a function to calculate them easily. summary_data_from_transaction_data function gives us a dataframe with frequency, recency, T and monetary_value columns. The function has “freq” feature that lets you to set a frequency. Options for “freq” are “D” for daily, ”W” for weekly, “M” for monthly and “Y” for yearly. I will set it to “W” to get weekly results.</p><p>frequency: How often a customer makes a purchase</p><p>recency: How recently a customer has made a purchase</p><p>T(tenure) : The customer age(for how many years has the customer been our customer)</p><p>monetary_value : Money value of the purchases</p><pre>cltv_df = summary_data_from_transaction_data(df, &#39;COMPANY_ID&#39;,&#39;INVOICE_DATE&#39;,&#39;TOTAL_PRICE&#39;, <br>                                                 include_first_transaction=True,<br>                                                 freq=&quot;W&quot;,<br>                                                observation_period_end = today_date)<br>cltv_df.describe().T</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*2bVZRqyCectC0bWUKawekA.png" /></figure><h3>Modeling and Evaluation</h3><p>BG-NBD stands for “Beta Geometric/Negative Binomial Distribution”. The BG/NBD model is based on the historical purchase behavior of each customer to forecast his future activity.</p><pre>bgf = BetaGeoFitter(penalizer_coef=0.001)<br>bgf.fit(cltv_df[&#39;frequency&#39;],<br>        cltv_df[&#39;recency&#39;],<br>        cltv_df[&#39;T&#39;])<br><br>ggf = GammaGammaFitter(penalizer_coef=0.01)<br>ggf.fit(cltv_df[&#39;frequency&#39;], cltv_df[&#39;monetary_value&#39;])<br><br>cltv = ggf.customer_lifetime_value(bgf,<br>                                   cltv_df[&#39;frequency&#39;],<br>                                   cltv_df[&#39;recency&#39;],<br>                                   cltv_df[&#39;T&#39;],<br>                                   cltv_df[&#39;monetary_value&#39;],<br>                                   time=4,  # 1 yıllık<br>                                   freq=&quot;W&quot;,  # T&#39;nin frekans bilgisi, haftalık:W<br>                                   discount_rate=0.01)<br>cltv=cltv.reset_index()<br>cltv_final= cltv_df.merge(cltv, on=&quot;COMPANY_ID&quot;, how=&quot;left&quot;)<br>cltv_final[&quot;COMPANY_ID&quot;] =cltv_final[&quot;COMPANY_ID&quot;].astype(int)<br>cltv_final.sort_values(&#39;clv&#39;, ascending=False).head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*G-KPmrnGbaCV2Zfw6Hdp1g.png" /></figure><h3>Segmentation according to CLTV values</h3><p>I will create segments based on CLV values.</p><pre>cltv_final[&quot;segment&quot;] = pd.qcut(cltv_final[&quot;clv&quot;], 4, labels=[&quot;D&quot;, &quot;C&quot;, &quot;B&quot;, &quot;A&quot;])<br>cltv_final[cltv_final[&quot;segment&quot;] ==&quot;A&quot;].sort_values(&#39;clv&#39;, ascending=False).head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*9RSlxWxqqZyiR4Ks6xw2HQ.png" /></figure><pre>cltv_final[cltv_final[&quot;segment&quot;] ==&quot;B&quot;].sort_values(&#39;clv&#39;, ascending=False).head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*NlVHADvqb13jJ5__Y_JPKg.png" /></figure><h3>Further Insights</h3><p><strong>Expected number of purchases with BG-NBD Model</strong></p><p>When we fit BetaGeoFitter model to the dataset, it will be enough for further steps of CLTV prediction. But I will apply some other functions on this model to have more insights about future purchases.</p><pre>from lifetimes.plotting import plot_frequency_recency_matrix<br>plot_frequency_recency_matrix(bgf,max_frequency=50, max_recency=50)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*nUK2e8sYwFrVp3D8pIASqQ.png" /></figure><pre>from lifetimes.plotting import plot_probability_alive_matrix<br>plot_probability_alive_matrix(bgf)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*8m0II3cK7934dT2qQm99dw.png" /></figure><p>The customers who have higher recency and higher frequency are expected to purchase more products. As frequency increases if recency is low, the probability of being alive is also low, if recency is high then the probability of being alive is higher. Actually to see the probability of being alive specific to each customer will be clarifying the second graph better. Thus I will look into the latency measure.</p><h4>Purchase Latency</h4><p>Purchase latency is a measure of the number of days between a customer’s orders. After the first order p_alive(probability of being alive) starts to occur for each customer. The average of the elapsed time between orders is recalculated for each order, resulting in a different p_alive.</p><p>If a customer orders after a long time, that is much more than the previous average time interval, the rate of decrease of p_alive value decreases in the next long interval. In other words the probability of being alive decreases more slowly. And then the average time interval and probability of being alive function is calculated again. This holds on again and again as long as customer goes on puschasing. As you will see the situation for the customer with COMPANY_ID = 12352 below.</p><pre>from matplotlib.pyplot import figure<br>from lifetimes.plotting import plot_history_alive<br>figure(num=None, figsize=(10, 4), dpi=80, facecolor=&#39;w&#39;, edgecolor=&#39;k&#39;)<br>days_since_birth = 700<br>plot_history_alive(bgf, days_since_birth, df.loc[df[&quot;COMPANY_ID&quot;] == 12352.00], &#39;INVOICE_DATE&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*ZiESPR40587uArcjFIkZSA.png" /></figure><p>Next, I will calculate expected number of purchases by using BG/NBD model and add it as a column to my dataframe.</p><pre>cltv_final[&quot;expected_purc_1_month&quot;] = bgf.conditional_expected_number_of_purchases_up_to_time(4,<br>                                               cltv_final[&#39;frequency&#39;],<br>                                               cltv_final[&#39;recency&#39;],<br>                                               cltv_final[&#39;T&#39;])</pre><h4>Testing purchase predictions with holdout group</h4><pre>from lifetimes.utils import calibration_and_holdout_data<br>from lifetimes.plotting import plot_calibration_purchases_vs_holdout_purchases<br><br>summary_cal_holdout = calibration_and_holdout_data(df, <br>                                                   &#39;COMPANY_ID&#39;, <br>                                                   &#39;INVOICE_DATE&#39;,<br>                                                    calibration_period_end=&#39;2011-08-01&#39;,<br>                                                    observation_period_end=today_date)<br>bgf.fit(summary_cal_holdout[&#39;frequency_cal&#39;], <br>       summary_cal_holdout[&#39;recency_cal&#39;], <br>      summary_cal_holdout[&#39;T_cal&#39;],<br>       tol=1e-04)<br><br>plot_calibration_purchases_vs_holdout_purchases(bgf, summary_cal_holdout)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*BGG3ipCIhfjCD4v0veVytg.png" /></figure><h4>GAMMA-GAMMA Model</h4><p>I will use Gamma-Gamma Model’s conditional_expected_average_profit function that calculates predicted average profit per transaction for each customer</p><pre>cltv_final[&quot;expected_average_profit&quot;] = ggf.conditional_expected_average_profit(cltv_final[&#39;frequency&#39;],<br>                                                                               cltv_final[&#39;monetary_value&#39;])<br>cltv_final.sort_values(&quot;expected_purc_1_month&quot;, ascending=False).head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*AF3z6fSW-OaTzTx8Gx3Riw.png" /></figure><h4>Conclusion</h4><p>In conclusion, I have predicted cltv, expected number of purchases and expected average profit for each curtomer for the next 4 weeks. Being aware of your best customers and predicting who is likely to churn might be useful to create different marketing strategies for different segments of customers. This model is quite simple to apply when compared to machine learning models but thus it has some disadvantages. For making predictions machine learning and deep learning models will work with better performance. But for CLTV calculation, customer segmentation and purchase latency measure this model may be among the options.</p><p>You can find the Jupyter Notebook for this article <a href="https://github.com/nesrinozcan/CRM/blob/main/cltv_prediction_bgnbd_gg.ipynb">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c98629710f39" width="1" height="1" alt=""><hr><p><a href="https://medium.com/akkimakademi/customer-lifetime-value-cltv-prediction-using-bg-nbd-and-gamma-gamma-models-in-python-c98629710f39">Customer Lifetime Value(CLTV) Prediction Using BG/NBD and Gamma Gamma Models in Python</a> was originally published in <a href="https://medium.com/akkimakademi">Akkim Akademi</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reshaping Tables With MultiIndex]]></title>
            <link>https://medium.com/akkimakademi/reshaping-tables-with-multiindex-8821828f6ac1?source=rss-c19af14c0bc2------2</link>
            <guid isPermaLink="false">https://medium.com/p/8821828f6ac1</guid>
            <dc:creator><![CDATA[Nesrin ÖZCAN]]></dc:creator>
            <pubDate>Thu, 20 Oct 2022 14:32:03 GMT</pubDate>
            <atom:updated>2022-10-21T11:24:58.661Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lZNYVXn90uWQ4MlqyoaBTg.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/cg_prodigy-8046899/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=4785225">Brian Ego</a> from <a href="https://pixabay.com//?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=4785225">Pixabay</a></figcaption></figure><p>Data manipulation is a significant step of data analysis process. While manipulating data, ‘Multi-level Indexing’ may allow you to take an alternative approach to the data. Using multi index sometimes seriously helps you to take a different aspect to the data, but sometimes it is a must. There are various ways for creating multi index and I will show some of them.</p><p>Firstly, I will import titanic dataset from Seaborn library. Using built-in datasets is a practical way of exercising for data analysis. I want to see the situation of “age” and “survived” variables according to “sex” and “class” varibles, so I selected only those columns from the dataset. I will show the first 5 rows with head() function to have a quick insight of the dataset.</p><pre>import seaborn as sns<br>df = sns.load_dataset(&quot;titanic&quot;)<br>df = df[[&quot;sex&quot;,&quot;class&quot;,&quot;age&quot;,&quot;survived&quot;]]<br>df.head(5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*-7Lb4AcrBf-aA9zWJF-h1w.png" /></figure><h3>pandas.DataFrame.set_index()</h3><p>Now, I will construct multi index with DataFrame.set_index() for “sex” and “class” columns in titanic dataset. set_index() function creates multi index, but it does not group by indexes with aggregation functions. This could be used to handle non-numeric data. If you want to apply aggregation functions on values, group_by() and pivot_table() functions will be useful.</p><pre>multiindex_set = df.iloc[:10,:].set_index([&quot;sex&quot;,&quot;class&quot;])<br>multiindex_set</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*ISKCnkDcBej9tY2E6WRYoA.png" /></figure><pre>multiindex_set.index</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*TCUvsWTpid9K8MeEDnb2bA.png" /></figure><h3>DataFrame.group_by() &amp; pandas.pivot_table()</h3><p>Pandas group_by() and pivot_table() functions allow us to apply aggregation functions over values according to indexes. Furthermore we can apply multiple types of aggregations for any column with the help of group_by() and pivot_table() functions.</p><pre>multiindex_groupby = df.groupby([&quot;sex&quot;,&quot;class&quot;]).agg({&quot;age&quot;:&quot;min&quot;,&quot;survived&quot;:&quot;median&quot;})<br>multiindex_groupby</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*tD_A5zwt2fAcJoTfp6hfrg.png" /></figure><pre>multiindex_groupby.index</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*gmFIxcsOdRPtJ7gA9Rgf_w.png" /></figure><pre>multiindex_pivottable = pd.pivot_table(df, values=[&quot;survived&quot;,&quot;age&quot;], index=[&quot;sex&quot;,&quot;class&quot;], aggfunc={&quot;age&quot;:[min,&quot;max&quot;,np.mean],&quot;survived&quot;:np.mean})<br>multiindex_pivottable</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*bO1tkGlpswyYRccUCJTwew.png" /></figure><p>Additionally, if we want to filter according to one or more index on a multi indexed dataframe, we can use iloc or loc for selection.</p><pre>multiindex_pivottable.loc[&quot;female&quot;,&quot;First&quot;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*tBzH-iX_UCclK3a9npk1Zg.png" /></figure><pre>multiindex_pivottable.iloc[1,2]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/136/1*83fzVi1khUsyGo3eqSjkwg.png" /></figure><p>There are many other issues about reshaping dataframes as a part of data analysis. I tried to show how to construct multi-indexed dataframes with some simple examples in my post. Thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8821828f6ac1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/akkimakademi/reshaping-tables-with-multiindex-8821828f6ac1">Reshaping Tables With MultiIndex</a> was originally published in <a href="https://medium.com/akkimakademi">Akkim Akademi</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating User Defined Functions(UDFs) and Lambda Expressions]]></title>
            <link>https://medium.com/akkimakademi/usage-of-user-defined-functions-and-lambda-expressions-16bc843235?source=rss-c19af14c0bc2------2</link>
            <guid isPermaLink="false">https://medium.com/p/16bc843235</guid>
            <dc:creator><![CDATA[Nesrin ÖZCAN]]></dc:creator>
            <pubDate>Thu, 01 Sep 2022 09:46:59 GMT</pubDate>
            <atom:updated>2022-09-01T14:19:00.809Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*dDDYv3CM6oHxs7K3nBLOmA.png" /></figure><p>Sometimes Python built-in functions are not sufficient for the project we are working on. At these times we need to create a new function that will satisfy our needs: User Defined Functions(UDF). However sometimes we look for an easier and more flexible way than writing a loop, here are the Lambda Expressions. I will try to show how to use UDFs and Lambda Expressions with some simple examples.</p><p>Firstly, let’s create a loop that takes the first three letters of each element in the list and capitalize them.</p><pre>months = [&quot;January&quot;, &quot;February&quot;, &quot;March&quot;]<br>for month in months:<br>    print(month[:3].upper())</pre><pre>Output:<br>JAN<br>FEB<br>MAR</pre><p>We can turn this loop into a function:</p><pre>def first_three_letter(list):<br>    for i in list:<br>        print(i[:3].upper())</pre><p>Let’s call the function:</p><pre>all_months = [&quot;January&quot;, &quot;February&quot;, &quot;March&quot;, &quot;April&quot;, &quot;May&quot;, &quot;June&quot;, &quot;July&quot;, &quot;August&quot;, &quot;September&quot;, &quot;October&quot;, &quot;November&quot;, &quot;December&quot;]<br>first_three_letter(all_months)</pre><pre>Output:<br>JAN<br>FEB<br>MAR<br>APR<br>MAY<br>JUN<br>JUL<br>AUG<br>SEP<br>OCT<br>NOV<br>DEC</pre><p>Now I will try to use my user defined function on a Pandas series object.</p><pre>import pandas as pd<br>ser=pd.Series(all_months)<br>first_three_letter(all_months)</pre><pre>Output:<br>JAN<br>FEB<br>MAR<br>APR<br>MAY<br>JUN<br>JUL<br>AUG<br>SEP<br>OCT<br>NOV<br>DEC</pre><p>Here is the usage of user defined function on a DataFrame column.</p><pre>df = pd.DataFrame({&quot;MonthName&quot;: [&quot;January&quot;, &quot;February&quot;, &quot;March&quot;], <br>                   &quot;MonthNumber&quot;: [1,2,3]})<br>first_three_letter(df[&quot;MonthName&quot;])</pre><pre>Output:<br>JAN<br>FEB<br>MAR</pre><h3><strong>Lambda Expressions</strong></h3><p>I can do the same calculation in the user defined function by using lambda expressions. A lambda expression is a function defined without a name.</p><p>Usually, normal functions are defined with the ‘def’ keyword but anonymous functions are defined by using the lambda function. By the way, ‘Lambda Expression’ and ‘Anonymous Function’ mean the same thing. They can be used interchangeably. Lambda expressions can be used in many ways. I can name it and call with this name as shown with a clear example:</p><pre>lambda_exp = lambda x: x[:3].upper()<br>lambda_exp(&quot;January&quot;)</pre><pre>Output:<br>&#39;JAN&#39;</pre><p>In order to use a lambda expression on a list, the map() function can come into play. This is another way of using lambda expressions. Map() is a built-in function that takes a function as a first argument and applies it to every element of its second argument, an iterable. This iterable can be list, string, series or tuple. Keep in mind that map() function returns an iterator, so you have to turn it into the intended format.</p><pre>map_fnc = map(lambda_exp,all_months)<br>print(list(map_fnc))</pre><pre>Output:<br>[&#39;JAN&#39;, &#39;FEB&#39;, &#39;MAR&#39;, &#39;APR&#39;, &#39;MAY&#39;, &#39;JUN&#39;, &#39;JUL&#39;, &#39;AUG&#39;, &#39;SEP&#39;, &#39;OCT&#39;, &#39;NOV&#39;, &#39;DEC&#39;]</pre><p>Lambda expressions can take multiple inputs like other functions. Let’s create a function that calculates volume of right cylinders. We need to import pi number from math module. Lambda expression will take two arguments; one is height and the other is radius of the cylinder.</p><pre>import math<br>math.pi<br>volume_of_cylinder = (lambda r,h: math.pi* (r**2) * h)<br>volume_of_cylinder(2,3)</pre><pre>Output:<br>37.69911184307752</pre><p>We can also use lambda expressions for filtering an iterable by using filter() function. Let’s filter a tuple that consists of radius and height knowledge of different cylinders. We want to see the values only if the volume of cylinder is less than 200. Firstly we will calculate all volumes and then filter them.</p><pre>radius_height = [(2,3),(5,2),(4,7),(3,5),(6,4),(3,6),(4,3),(7,5),(9,4),(4,4),(5,5),(7,3)]<br>list(map(lambda x : (math.pi* (x[0]**2) * x[1]), radius_height))</pre><pre>Output:<br>[37.69911184307752,<br> 157.07963267948966,<br> 351.85837720205683,<br> 141.3716694115407,<br> 452.3893421169302,<br> 169.64600329384882,<br> 150.79644737231007,<br> 769.6902001294993,<br> 1017.8760197630929,<br> 201.06192982974676,<br> 392.69908169872417,<br> 461.81412007769956]<br></pre><pre>list(filter(lambda x : (math.pi* (x[0]**2) * x[1]) &gt; 200, radius_height))</pre><pre>Output:<br>[(4, 7), (6, 4), (7, 5), (9, 4), (4, 4), (5, 5), (7, 3)]</pre><h3><strong>Use Lambda Expression as an anonymous function inside another function</strong></h3><p>Lambda expressions can be used inside another function. Let’s create a power function that takes two arguments a and n, where a is multiplied by itself n times.</p><pre>def power(a,n):<br>    return a**n<br>print(power(2,2))<br>print(power(2,3))</pre><pre>Output:<br>4<br>8</pre><p>To be able to create different functions from this power(a,n) function, a lambda expression can be used inside the function.<br>Lambda expression gives the flexibility to create different functions by changing the anonymous function.</p><pre>def power(n):<br>    return lambda a: a**n<br>power2=power(2)<br>power3=power(3)<br>print(power2(2))<br>print(power3(2))</pre><pre>Output:<br>4<br>8</pre><p>I tried to show you how to use ‘Lambda Expressions’ and ‘User Defined Functions’ with some simple examples. Thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16bc843235" width="1" height="1" alt=""><hr><p><a href="https://medium.com/akkimakademi/usage-of-user-defined-functions-and-lambda-expressions-16bc843235">Creating User Defined Functions(UDFs) and Lambda Expressions</a> was originally published in <a href="https://medium.com/akkimakademi">Akkim Akademi</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>