{"id":127407,"date":"2022-08-20T16:13:15","date_gmt":"2022-08-20T16:13:15","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=595293"},"modified":"2022-08-20T16:13:15","modified_gmt":"2022-08-20T16:13:15","slug":"how-to-apply-a-function-to-each-cell-in-a-pandas-dataframe","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2022\/08\/20\/how-to-apply-a-function-to-each-cell-in-a-pandas-dataframe\/","title":{"rendered":"How to Apply a Function to Each Cell in a Pandas DataFrame?"},"content":{"rendered":"\n<div class=\"kk-star-ratings kksr-auto kksr-align-left kksr-valign-top\" data-payload=\"{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;595293&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;1&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\\\/5 - (1 vote)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\\\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}\">\n<div class=\"kksr-stars\">\n<div class=\"kksr-stars-inactive\">\n<div class=\"kksr-star\" data-star=\"1\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"2\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"3\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"4\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"5\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<div class=\"kksr-stars-active\" style=\"width: 142.5px;\">\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<\/div>\n<div class=\"kksr-legend\" style=\"font-size: 19.2px;\"> 5\/5 &#8211; (1 vote) <\/div>\n<\/div>\n<h2>Problem Formulation<\/h2>\n<p>Given the following DataFrame <code>df<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import pandas as pd df = pd.DataFrame([{'A':1, 'B':2, 'C':2, 'D':4}, {'A':4, 'B':8, 'C':3, 'D':1}, {'A':2, 'B':7, 'C':1, 'D':2}, {'A':3, 'B':5, 'C':1, 'D':2}]) print(df) ''' A B C D\n0 1 2 2 4\n1 4 8 3 1\n2 2 7 1 2\n3 3 5 1 2 '''<\/pre>\n<p class=\"has-global-color-8-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f4ac.png\" alt=\"\ud83d\udcac\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Challenge<\/strong>: How to apply a function <code>f<\/code> to each cell in the DataFrame? <\/p>\n<p>For example, you may want to apply a function that replaces all odd values with the value <code>'odd'<\/code>.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"16\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import pandas as pd df = pd.DataFrame([{'A':1, 'B':2, 'C':2, 'D':4}, {'A':4, 'B':8, 'C':3, 'D':1}, {'A':2, 'B':7, 'C':1, 'D':2}, {'A':3, 'B':5, 'C':1, 'D':2}]) def f(cell): if cell%2 == 1: return 'odd' return cell # ... &lt;Apply Function f to each cell> ... print(df) ''' A B C D\n0 odd 2 2 4\n1 4 8 odd odd\n2 2 odd odd 2\n3 odd odd odd 2 '''<\/pre>\n<h2>Solution: DataFrame applymap()<\/h2>\n<p class=\"has-global-color-8-background-color has-background\">The Pandas DataFrame <code>df.applymap()<\/code> method returns a new DataFrame where the function <code>f<\/code> is applied to each cell of the original DataFrame <code>df<\/code>. You can pass any function object as a single argument into the <code>df.applymap()<\/code> function, either defined as a lambda expression or a normal function.<\/p>\n<h2>Example 1: Replace Odd Values in DataFrame<\/h2>\n<p>Here&#8217;s an example where each cell of the DataFrame is checked against whether it is an odd value. If so, it is replaced with the string <code>'odd'<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def f(cell): if cell%2 == 1: return 'odd' return cell df_new = df.applymap(f) print(df_new) ''' A B C D\n0 odd 2 2 4\n1 4 8 odd odd\n2 2 odd odd 2\n3 odd odd odd 2 '''\n<\/pre>\n<h2>Example 2: Create Two DataFrames with Even and Odd Values Replaced<\/h2>\n<p>A slightly advanced example uses two <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/a-simple-introduction-of-the-lambda-function-in-python\/\" data-type=\"post\" data-id=\"2701\" target=\"_blank\">lambda functions<\/a> to create two new DataFrames where one has all odd and the other has all even values replaced:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"10,11\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import pandas as pd df = pd.DataFrame([{'A':1, 'B':2, 'C':2, 'D':4}, {'A':4, 'B':8, 'C':3, 'D':1}, {'A':2, 'B':7, 'C':1, 'D':2}, {'A':3, 'B':5, 'C':1, 'D':2}]) df_even = df.applymap(lambda x: 'odd' if x%2 else x)\ndf_odd = df.applymap(lambda x: x if x%2 else 'even') print(df_even) ''' A B C D\n0 odd 2 2 4\n1 4 8 odd odd\n2 2 odd odd 2\n3 odd odd odd 2 ''' print(df_odd) ''' A B C D\n0 1 even even even\n1 even even 3 1\n2 even 7 1 even\n3 3 5 1 even '''<\/pre>\n<p>We used the concept of a <strong><em>ternary operator<\/em><\/strong> to concisely define the replacement function using the keyword <code><a href=\"https:\/\/blog.finxter.com\/python-ternary-lambda\/\" data-type=\"post\" data-id=\"10752\" target=\"_blank\" rel=\"noreferrer noopener\">lambda<\/a><\/code> to create a function object &#8220;on the fly&#8221;. <\/p>\n<p class=\"has-base-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f30d.png\" alt=\"\ud83c\udf0d\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Recommended Tutorial<\/strong>: <a href=\"https:\/\/blog.finxter.com\/python-one-line-ternary\/\" data-type=\"post\" data-id=\"10641\">Understanding the Ternary Operator in Python<\/a><\/p>\n<p>This tutorial idea was proposed by <a href=\"https:\/\/blog.finxter.com\/email-academy\/\" data-type=\"page\" data-id=\"12278\" target=\"_blank\" rel=\"noreferrer noopener\">Finxter student<\/a> <strong>Kyriakos<\/strong>. <img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/2764.png\" alt=\"\u2764\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/><\/p>\n","protected":false},"excerpt":{"rendered":"<p>5\/5 &#8211; (1 vote) Problem Formulation Given the following DataFrame df: import pandas as pd df = pd.DataFrame([{&#8216;A&#8217;:1, &#8216;B&#8217;:2, &#8216;C&#8217;:2, &#8216;D&#8217;:4}, {&#8216;A&#8217;:4, &#8216;B&#8217;:8, &#8216;C&#8217;:3, &#8216;D&#8217;:1}, {&#8216;A&#8217;:2, &#8216;B&#8217;:7, &#8216;C&#8217;:1, &#8216;D&#8217;:2}, {&#8216;A&#8217;:3, &#8216;B&#8217;:5, &#8216;C&#8217;:1, &#8216;D&#8217;:2}]) print(df) &#8221;&#8217; A B C D 0 1 2 2 4 1 4 8 3 1 2 2 7 1 2 3 [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-127407","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/127407","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=127407"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/127407\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=127407"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=127407"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=127407"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}