{"id":112060,"date":"2020-04-26T14:29:24","date_gmt":"2020-04-26T14:29:24","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=7925"},"modified":"2020-04-26T14:29:24","modified_gmt":"2020-04-26T14:29:24","slug":"how-to-convert-list-of-lists-to-numpy-array","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/04\/26\/how-to-convert-list-of-lists-to-numpy-array\/","title":{"rendered":"How to Convert List of Lists to NumPy Array?"},"content":{"rendered":"<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<div class=\"ast-oembed-container\"><iframe loading=\"lazy\" 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>\n<\/div>\n<\/figure>\n<p><strong>Short answer: Convert a list of lists&#8212;let&#8217;s call it <code>l<\/code>&#8212;to a NumPy array by using the standard <code>np.array(l)<\/code> function. This works even if the inner lists have a different number of elements.<\/strong><\/p>\n<h2>Convert List of Lists to 2D Array<\/h2>\n<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>\n<p><strong>Example<\/strong>: Convert the following list of lists<\/p>\n<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>\n<p>into a NumPy array<\/p>\n<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>\n<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&#8217;s the code:<\/p>\n<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\nimport numpy as np # Create the list of lists\nlst = [[1, 2, 3], [4, 5, 6]] # Convert it to a NumPy array\na = np.array(lst) # Print the resulting array\nprint(a) '''\n[[1 2 3] [4 5 6]] '''<\/pre>\n<p><strong>Try It Yourself<\/strong>: Here&#8217;s the same code in our interactive code interpreter:<\/p>\n<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>\n<p><strong>Hint<\/strong>: The NumPy method <code>np.array()<\/code> takes an iterable as input and converts it into a NumPy array. <\/p>\n<h2>Convert a List of Lists With Different Number of Elements<\/h2>\n<p><strong>Problem<\/strong>: Given a list of lists. The inner lists have a varying number of elements. How to convert them to a NumPy array?<\/p>\n<p><strong>Example<\/strong>: Say, you&#8217;ve got the following list of lists:<\/p>\n<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>\n<p>What are the different approaches to convert this list of lists into a NumPy array?<\/p>\n<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>\n<p><strong>(1) Use the standard <code>np.array()<\/code> function. <\/strong><\/p>\n<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\nimport numpy as np # Create the list of lists\nlst = [[1, 2, 3], [4, 5], [6, 7, 8]] # Convert it to a NumPy array\na = np.array(lst) # Print the resulting array\nprint(a) '''\n[list([1, 2, 3]) list([4, 5]) list([6, 7, 8])] '''<\/pre>\n<p>This creates a NumPy array with three elements&#8212;each element is a list type. You can check the type of the output by using the built-in <code>type()<\/code> function:<\/p>\n<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)\n&lt;class 'numpy.ndarray'><\/pre>\n<p><strong>(2) Make an array of arrays.<\/strong><\/p>\n<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\nimport numpy as np # Create the list of lists\nlst = [[1, 2, 3], [4, 5], [6, 7, 8]] # Convert it to a NumPy array\na = np.array([np.array(x) for x in lst]) # Print the resulting array\nprint(a) '''\n[array([1, 2, 3]) array([4, 5]) array([6, 7, 8])] '''<\/pre>\n<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>\n<p><strong>(3) Make the lists equal in length.<\/strong><\/p>\n<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\nimport numpy as np # Create the list of lists\nlst = [[1, 2, 3], [4, 5], [6, 7, 8, 9]] # Calculate length of maximal list\nn = len(max(lst, key=len)) # Make the lists equal in length\nlst_2 = [x + [None]*(n-len(x)) for x in lst]\nprint(lst_2)\n# [[1, 2, 3, None], [4, 5, None, None], [6, 7, 8, 9]] # Convert it to a NumPy array\na = np.array(lst_2) # Print the resulting array\nprint(a) '''\n[[1 2 3 None] [4 5 None None] [6 7 8 9]] '''\n<\/pre>\n<p>You use <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/list-comprehension\/\" target=\"_blank\">list comprehension<\/a> to &#8220;pad&#8221; <code>None<\/code> values to each inner list with smaller than maximal length.<\/p>\n<h2>Where to Go From Here?<\/h2>\n<p>Enough theory, let\u2019s get some practice!<\/p>\n<p>To become successful in coding, you need to get out there and solve real problems for real people. That\u2019s how you can become a six-figure earner easily. And that\u2019s how you polish the skills you really need in practice. After all, what\u2019s the use of learning theory that nobody ever needs?<\/p>\n<p><strong>Practice projects is how you sharpen your saw in coding!<\/strong><\/p>\n<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>\n<p>Then become a Python freelance developer! It\u2019s the best way of approaching the task of improving your Python skills\u2014even if you are a complete beginner.<\/p>\n<p>Join my free webinar <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\">\u201cHow to Build Your High-Income Skill Python\u201d<\/a> and watch how I grew my coding business online and how you can, too\u2014from the comfort of your own home.<\/p>\n<p><a href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\" rel=\"noreferrer noopener\">Join the free webinar now!<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Short answer: Convert a list of lists&#8212;let&#8217;s call it l&#8212;to a NumPy array by using the standard np.array(l) function. This works even if the inner lists have a different number of elements. Convert List of Lists to 2D Array Problem: Given a list of lists in Python. How to convert it to a 2D NumPy [&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-112060","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\/112060","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=112060"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/112060\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=112060"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=112060"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=112060"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}