Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Convert a List to a NumPy Array?

#1
How to Convert a List to a NumPy Array?

<div><p><strong>To convert a Python list to a NumPy array, use either of the following two methods:</strong></p>
<ol>
<li><strong>The <code>np.array()</code> function that takes an iterable and returns a NumPy array creating a new data structure in memory</strong>.</li>
<li><strong>The <code>np.asarray()</code> function that takes an iterable as argument and converts it to the array. The difference to <code>np.array()</code> is that <code>np.asarray()</code> doesn’t create a new copy in memory if you pass a NumPy array. All changes made on the original array are reflected on the NumPy array.</strong></li>
</ol>
<p> <iframe src="https://trinket.io/embed/python/2c445ee795" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </p>
<p><em><strong>Exercise</strong>: Create array <code>b</code> from array <code>a</code> using both methods. Then change a value in array <code>a</code>. What happens at array <code>b</code>?</em></p>
<h2>NumPy vs Python Lists</h2>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="What are Advantages of NumPy over Regular Python Lists?" width="1400" height="788" src="https://www.youtube.com/embed/MKOw9ATtVqE?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p>The Python built-in <a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener">list data type</a> is powerful. However, the <a href="https://blog.finxter.com/numpy-tutorial/" target="_blank" rel="noreferrer noopener">NumPy array</a> has many advantages over Python lists. What are they?</p>
<figure class="wp-block-table is-style-stripes">
<table>
<thead>
<tr>
<th>Advantages NumPy</th>
<th>Advantages Python Lists</th>
</tr>
</thead>
<tbody>
<tr>
<td>Multi-dimensional Slicing</td>
<td>Library-Independent</td>
</tr>
<tr>
<td>Broadcasting Functionality</td>
<td>Intuitive</td>
</tr>
<tr>
<td>Processing Speed</td>
<td>Less Complicated</td>
</tr>
<tr>
<td>Memory Footprint</td>
<td>Heterogeneous List Data Allowed</td>
</tr>
<tr>
<td>Many Convenience Methods</td>
<td>Arbitrary Data Shape (Non-Square Matrix)</td>
</tr>
</tbody>
</table>
</figure>
<p>To read more about the advantages of a NumPy array over a Python list,<a rel="noreferrer noopener" href="https://blog.finxter.com/what-are-advantages-of-numpy-over-regular-python-lists/" target="_blank"> read my detailed blog tutorial.</a></p>
<h2>How to Convert a 1D Python List to a NumPy Array?</h2>
<p><strong>Problem</strong>: Given a one-dimensional Python list. How to convert it to a NumPy array?</p>
<p><strong>Example</strong>: You have the following 1D Python list of integers.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">lst = [0, 1, 100, 42, 13, 7]</pre>
<p>You want to convert it into a NumPy array.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">array([ 0, 1, 100, 42, 13, 7])</pre>
<h3>Method 1: np.array(…Wink</h3>
<p>The simplest way to convert a Python list to a NumPy array is to use the <code>np.array()</code> function that takes an iterable and returns a NumPy array. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np
lst = [0, 1, 100, 42, 13, 7]
print(np.array(lst))</pre>
<p>The output is:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># [ 0 1 100 42 13 7]</pre>
<p>This creates a new data structure in memory. Changes on the original list are not visible to the variable that holds the NumPy array:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">lst = [0, 1, 100, 42, 13, 7]
a = np.array(lst)
lst.append(999)
print(a)
# [ 0 1 100 42 13 7]</pre>
<p>The element <code>999</code> which is now part of list <code>lst</code> is not part of array <code>a</code>. </p>
<h3>Method 2: np.asarray(…Wink</h3>
<p>An alternative is to use the <code>np.asarray()</code> function that takes one argument—the iterable—and converts it to the NumPy array. The difference to <code>np.array()</code> is that it doesn’t create a new copy in memory IF you pass a NumPy array. All changes made on the original array are reflected on the NumPy array! So be careful.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">lst = [0, 1, 100, 42, 13, 7]
a = np.array(lst)
b = np.asarray(a)
a[0] = 99
print(b)
# [ 99 1 100 42 13 7]</pre>
<p>The array <code>b</code> is created using the <code>np.asarray()</code> function, so if you change a value of array <code>a</code>, the change will be reflected on the variable <code>b</code> (because they point to the same object in memory).</p>
<h2>[Video] How to Convert a List of Lists to a NumPy Array?</h2>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="How to Convert List of Lists to NumPy Array?" width="1400" height="788" src="https://www.youtube.com/embed/bnLjhPTw_HU?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<h2>Convert List of Lists to 2D Array</h2>
<p><strong>Problem</strong>: Given a <a href="https://blog.finxter.com/python-list-of-lists/" target="_blank" rel="noreferrer noopener">list of lists</a> in Python. How to convert it to a 2D <a href="https://blog.finxter.com/numpy-tutorial/" target="_blank" rel="noreferrer noopener">NumPy array</a>?</p>
<p><strong>Example</strong>: Convert the following list of lists</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[[1, 2, 3], [4, 5, 6]]</pre>
<p>into a NumPy array</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[[1 2 3] [4 5 6]]</pre>
<p><strong>Solution</strong>: Use the <code>np.array(list)</code> function to convert a list of lists into a two-dimensional NumPy array. Here’s the code:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Import the NumPy library
import numpy as np # Create the list of lists
lst = [[1, 2, 3], [4, 5, 6]] # Convert it to a NumPy array
a = np.array(lst) # Print the resulting array
print(a) '''
[[1 2 3] [4 5 6]] '''</pre>
<p><strong>Try It Yourself</strong>: Here’s the same code in our interactive code interpreter:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;iframe height="700px" width="100%" src="https://repl.it/@finxter/numpylistoflists?lite=true" scrolling="no" frameborder="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals">&lt;/iframe></pre>
<p><strong>Hint</strong>: The NumPy method <code>np.array()</code> takes an iterable as input and converts it into a NumPy array. </p>
<h2>Convert a List of Lists With Different Number of Elements</h2>
<p><strong>Problem</strong>: Given a <a href="https://blog.finxter.com/copy-list-of-lists-in-python-shallow-vs-deep/" target="_blank" rel="noreferrer noopener">list of lists</a>. The inner lists have a varying number of elements. How to convert them to a NumPy array?</p>
<p><strong>Example</strong>: Say, you’ve got the following list of lists:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[[1, 2, 3], [4, 5], [6, 7, 8]]</pre>
<p>What are the different approaches to convert this list of lists into a NumPy array?</p>
<p><strong>Solution</strong>: There are three different strategies you can use. (<a rel="noreferrer noopener" href="https://stackoverflow.com/questions/10346336/list-of-lists-into-numpy-array" target="_blank">source</a>) </p>
<p><strong>(1) Use the standard <code>np.array()</code> function. </strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Import the NumPy library
import numpy as np # Create the list of lists
lst = [[1, 2, 3], [4, 5], [6, 7, 8]] # Convert it to a NumPy array
a = np.array(lst) # Print the resulting array
print(a) '''
[list([1, 2, 3]) list([4, 5]) list([6, 7, 8])] '''</pre>
<p>This creates a NumPy array with three elements—each element is a list type. You can check the type of the output by using the built-in <code>type()</code> function:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> type(a)
&lt;class 'numpy.ndarray'></pre>
<p><strong>(2) Make an array of arrays.</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Import the NumPy library
import numpy as np # Create the list of lists
lst = [[1, 2, 3], [4, 5], [6, 7, 8]] # Convert it to a NumPy array
a = np.array([np.array(x) for x in lst]) # Print the resulting array
print(a) '''
[array([1, 2, 3]) array([4, 5]) array([6, 7, 8])] '''</pre>
<p>This is more logical than the previous version because it creates a NumPy array of 1D NumPy arrays (rather than 1D Python lists). </p>
<p><strong>(3) Make the lists equal in length.</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Import the NumPy library
import numpy as np # Create the list of lists
lst = [[1, 2, 3], [4, 5], [6, 7, 8, 9]] # Calculate length of maximal list
n = len(max(lst, key=len)) # Make the lists equal in length
lst_2 = [x + [None]*(n-len(x)) for x in lst]
print(lst_2)
# [[1, 2, 3, None], [4, 5, None, None], [6, 7, 8, 9]] # Convert it to a NumPy array
a = np.array(lst_2) # Print the resulting array
print(a) '''
[[1 2 3 None] [4 5 None None] [6 7 8 9]] '''
</pre>
<p>You use <a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" target="_blank">list comprehension</a> to “pad” <code>None</code> values to each inner list with smaller than maximal length.</p>
<p>Related Articles</p>
<ul>
<li><a href="https://blog.finxter.com/how-to-convert-list-of-lists-to-numpy-array/" target="_blank" rel="noreferrer noopener">How to Convert a List of Lists to a NumPy array?</a></li>
<li><a href="https://blog.finxter.com/what-are-advantages-of-numpy-over-regular-python-lists/" target="_blank" rel="noreferrer noopener">What are Advantages of NumPy arrays over Python lists?</a></li>
</ul>
<h2>Where to Go From Here?</h2>
<p>Enough theory, let’s get some practice!</p>
<p>To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?</p>
<p><strong>Practice projects is how you sharpen your saw in coding!</strong></p>
<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?</p>
<p>Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.</p>
<p>Join my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and watch how I grew my coding business online and how you can, too—from the comfort of your own home.</p>
<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p></p>
</div>


https://www.sickgaming.net/blog/2020/06/...mpy-array/
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016