{"id":11017,"date":"2020-11-30T16:41:28","date_gmt":"2020-11-30T16:41:28","guid":{"rendered":"https:\/\/www.askpython.com\/?p=11017"},"modified":"2023-02-16T19:56:57","modified_gmt":"2023-02-16T19:56:57","slug":"python-astype","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/built-in-methods\/python-astype","title":{"rendered":"Python astype() &#8211; Type Conversion of Data columns"},"content":{"rendered":"\n<p>In this article, we will work on an important concept &#8211; <strong>Data Type Conversion of columns in a DataFrame using Python astype() method<\/strong> in detail.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Understanding Python astype() function<\/h2>\n\n\n\n<p>Before diving deep into the concept of Data type conversion with the Python astype() method, let us first consider the below scenario.<\/p>\n\n\n\n<p>In the domain of Data Science and Machine Learning, we often come across a stage where we need to pre-process and transform the data. In fact, to be precise, the transformation of data values is the keen step towards modeling.<\/p>\n\n\n\n<p>This is when Conversion of data columns comes into picture.<\/p>\n\n\n\n<p><strong>Python astype() method enables us to set or convert the data type of an existing data column in a dataset or a data frame.<\/strong> <\/p>\n\n\n\n<p>By this, we can change or transform the type of the data values or single or multiple columns to altogether another form using astype() function.<\/p>\n\n\n\n<p>Let us now focus on the syntax of astype() function in detail in the upcoming section.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Syntax &#8211; astype() function<\/h2>\n\n\n\n<p>Have a look at the below syntax!<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nDataFrame.astype(dtype, copy=True, errors=\u2019raise\u2019)\n<\/pre><\/div>\n\n\n<ul class=\"wp-block-list\"><li><strong>dtype<\/strong>: The data type we want to apply to the entire data frame.<\/li><li><strong>copy<\/strong>: By setting it to <strong>True<\/strong>, it creates another copy of the dataset inculcating the changes to it.<\/li><li><strong>errors<\/strong>: By setting it to &#8216;<strong>raise<\/strong>&#8216;, we allow the exceptions to be raised by the function. If not, we can set it to &#8216;<strong>ignore<\/strong>&#8216;.<\/li><\/ul>\n\n\n\n<p>Having understood the syntax of the function, let us now focus on the implementation of the same!<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">1. Python astype() with a DataFrame<\/h3>\n\n\n\n<p>In this example, we have created a <a aria-label=\"DataFrame (opens in a new tab)\" href=\"https:\/\/www.askpython.com\/python-modules\/pandas\/dataframes-in-python\" target=\"_blank\" rel=\"noreferrer noopener\" class=\"rank-math-link\">DataFrame<\/a> from the <a href=\"https:\/\/www.askpython.com\/python\/dictionary\/python-dictionary-dict-tutorial\" target=\"_blank\" aria-label=\"dictionary  (opens in a new tab)\" rel=\"noreferrer noopener\" class=\"rank-math-link\">dictionary <\/a>as shown below using <code>pandas.DataFrame() <\/code>method.<\/p>\n\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport pandas as pd \ndata = {&quot;Gender&quot;:&#x5B;&#039;M&#039;,&#039;F&#039;,&#039;F&#039;,&#039;M&#039;,&#039;F&#039;,&#039;F&#039;,&#039;F&#039;], &quot;NAME&quot;:&#x5B;&#039;John&#039;,&#039;Camili&#039;,&#039;Rheana&#039;,&#039;Joseph&#039;,&#039;Amanti&#039;,&#039;Alexa&#039;,&#039;Siri&#039;]}\n\nblock = pd.DataFrame(data)\nprint(&quot;Original Data frame:\\n&quot;)\nprint(block)\nblock.dtypes\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<p>Let us have a look at the original data types of the keys.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nOriginal Data frame:\n\n  Gender    NAME\n0      M    John\n1      F  Camili\n2      F  Rheana\n3      M  Joseph\n4      F  Amanti\n5      F   Alexa\n6      F    Siri\n\nGender    object\nNAME      object\ndtype: object\n<\/pre><\/div>\n\n\n<p>Now, we have applied astype() method on the &#8216;Gender&#8217; column and have changed the data type to &#8216;category&#8217;.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nblock&#x5B;&#039;Gender&#039;] = block&#x5B;&#039;Gender&#039;].astype(&#039;category&#039;)\nblock.dtypes\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nGender    category\nNAME        object\ndtype: object\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>2. Implementing Python astype() with a Dataset<\/strong><\/h3>\n\n\n\n<p>Here, we have imported the dataset using <a aria-label=\"pandas.read_csv() (opens in a new tab)\" rel=\"noreferrer noopener\" href=\"https:\/\/www.askpython.com\/python-modules\/python-csv-module\" target=\"_blank\" class=\"rank-math-link\">pandas.read_csv()<\/a> function. You can find the dataset here. <\/p>\n\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport pandas \nBIKE = pandas.read_csv(&quot;Bike.csv&quot;)\nBIKE.dtypes\n<\/pre><\/div>\n\n\n<p><strong>The original data types of the columns&#8211;<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ntemp            float64\nhum             float64\nwindspeed       float64\ncnt               int64\nseason_1          int64\nseason_2          int64\nseason_3          int64\nseason_4          int64\nyr_0              int64\nyr_1              int64\nmnth_1            int64\nmnth_2            int64\nmnth_3            int64\nmnth_4            int64\nmnth_5            int64\nmnth_6            int64\nmnth_7            int64\nmnth_8            int64\nmnth_9            int64\nmnth_10           int64\nmnth_11           int64\nmnth_12           int64\nweathersit_1      int64\nweathersit_2      int64\nweathersit_3      int64\nholiday_0         int64\nholiday_1         int64\ndtype: object\n<\/pre><\/div>\n\n\n<p>Now, we have tried to change the data type of the variables &#8216;season_1&#8217; and &#8216;temp&#8217;. Thus, we say that with astype() function, we can change the data types of multiple columns in a single go!<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nBIKE = BIKE.astype({&quot;season_1&quot;:&#039;category&#039;, &quot;temp&quot;:&#039;int64&#039;}) \nBIKE.dtypes\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ntemp               int64\nhum              float64\nwindspeed        float64\ncnt                int64\nseason_1        category\nseason_2           int64\nseason_3           int64\nseason_4           int64\nyr_0               int64\nyr_1               int64\nmnth_1             int64\nmnth_2             int64\nmnth_3             int64\nmnth_4             int64\nmnth_5             int64\nmnth_6             int64\nmnth_7             int64\nmnth_8             int64\nmnth_9             int64\nmnth_10            int64\nmnth_11            int64\nmnth_12            int64\nweathersit_1       int64\nweathersit_2       int64\nweathersit_3       int64\nholiday_0          int64\nholiday_1          int64\ndtype: object\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>By this, we have come to the end of this topic. Feel free to comment below, in case you come across any question.<\/p>\n\n\n\n<p>For more such posts related to Python, Stay tuned and till then, Happy learning!! \ud83d\ude42<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we will work on an important concept &#8211; Data Type Conversion of columns in a DataFrame using Python astype() method in detail. Understanding Python astype() function Before diving deep into the concept of Data type conversion with the Python astype() method, let us first consider the below scenario. In the domain of [&hellip;]<\/p>\n","protected":false},"author":4,"featured_media":11049,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[8],"tags":[],"class_list":["post-11017","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-built-in-methods"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/11017","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/4"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=11017"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/11017\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/11049"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=11017"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=11017"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=11017"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}