Python Pandas - Create a DataFrame from original index but enforce a new index

PythonServer Side ProgrammingProgramming

<p>To create a DataFrame from original index but enforce a new index, use the index.to_frame(). Set the parameter <strong>index</strong> to <strong>False</strong>.</p><p>At first, import the required libraries &minus;</p><pre class="just-code notranslate language-python3" data-lang="python3">import pandas as pd</pre><p>Creating Pandas index &minus;</p><pre class="just-code notranslate language-python3" data-lang="python3">index = pd.Index([&#39;Electronics&#39;,&#39;Accessories&#39;,&#39;Decor&#39;, &#39;Books&#39;, &#39;Toys&#39;],name =&#39;Products&#39;)</pre><p>Display the Pandas index</p><pre class="just-code notranslate language-python3" data-lang="python3">print(&quot;Pandas Index... &quot;,index) </pre><p>Enforce new index and convert index to DataFrame. Here, the actual index gets replaced by another index &minus;</p><pre class="just-code notranslate language-python3python" data-lang="python3">print(&quot; Index to DataFrame... &quot;,index.to_frame(index=False))</pre><h2>Example</h2><p>Following is the code &minus;</p><pre class="demo-code notranslate language-python3" data-lang="python3">import pandas as pd # Creating Pandas index index = pd.Index([&#39;Electronics&#39;,&#39;Accessories&#39;,&#39;Decor&#39;, &#39;Books&#39;, &#39;Toys&#39;],name =&#39;Products&#39;) # Display the Pandas index print(&quot;Pandas Index... &quot;,index) # Return the number of elements in the Index print(&quot; Number of elements in the index... &quot;,index.size) # Return the dtype of the data print(&quot; The dtype object... &quot;,index.dtype) # Enforce new index and convert index to DataFrame # Here, the actual index gets replaced by another index print(&quot; Index to DataFrame... &quot;,index.to_frame(index=False))</pre><h2>Output</h2><p>This will produce the following output &minus;</p><pre class="result notranslate">Pandas Index... Index([&#39;Electronics&#39;, &#39;Accessories&#39;, &#39;Decor&#39;, &#39;Books&#39;, &#39;Toys&#39;], dtype=&#39;object&#39;, name=&#39;Products&#39;) Number of elements in the index... 5 The dtype object... object Index to DataFrame... &nbsp; &nbsp; &nbsp; Products 0 &nbsp;Electronics 1 &nbsp;Accessories 2 &nbsp; &nbsp; &nbsp; Decor 3 Books 4 Toys</pre>
raja
Updated on 13-Oct-2021 09:56:16

Advertisements