Python Pandas - Get integer location for requested label and find the previous index value if no exact match

PythonPandasServer Side ProgrammingProgramming

<p>To get integer location for requested label and find the previous index value if no exact match, use the <strong>index.get_loc()</strong>. Set the parameter <strong>method</strong> to the value <strong>ffill</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([10, 20, 30, 40, 50, 60, 70])</pre><p>Display the Pandas index &minus;</p><pre class="just-code notranslate language-python3" data-lang="python3">print(&quot;Pandas Index... &quot;,index)</pre><p>Get the location of the previous index if no exact match. The value is set &quot;ffill&quot; using the &quot;method&quot; parameter of the get_loc() &minus;</p><pre class="just-code notranslate language-python3python" data-lang="python3">print(&quot; Get the location of the previous index if no exact match... &quot;, index.get_loc(45, method=&quot;ffill&quot;))</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([10, 20, 30, 40, 50, 60, 70]) # 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) # get integer location from the given index print(&quot; Display integer location from given index... &quot;,index.get_loc(20)) print(&quot; Display integer location from given index... &quot;,index.get_loc(50)) # Get the location of the previous index if no exact match # The value is set &quot;ffill&quot; using the &quot;method&quot; parameter of the get_loc() print(&quot; Get the location of the previous index if no exact match... &quot;, index.get_loc(45, method=&quot;ffill&quot;))</pre><h2>Output</h2><p>This will produce the following output &minus;</p><pre class="result notranslate">Pandas Index... Int64Index([10, 20, 30, 40, 50, 60, 70], dtype=&#39;int64&#39;) Number of elements in the index... 7 Display integer location from given index... 1 Display integer location from given index... 4 Get the location of the previous index if no exact match... 3</pre>
raja
Updated on 14-Oct-2021 08:47:13

Advertisements