Reshaping allows to change the shape of an array. For example, we can reshape a two dimensional array into a one dimensional one and vice versa
1 2 3 4 5 6 7 8 9 10 |
import scrapy class QuotesToScrape(scrapy.Spider): name = "quotes_to_scrape" start_urls = ["http://quotes.toscrape.com/"] def parse(Self, response): yield { 'quote_text': quote.xpath(".//span[@class='text']/text()").extract_first() } |
Change a one dimensional array into two dimensional
We can use the reshape method to covert a one dimensional array into two dimensional array.
1 2 3 4 5 6 7 8 9 10 11 |
# import numpy library as np import numpy as np # Create an array one_dim = np.array([1,2,3,4,5,6,7,8,9,10]) print(one_dim) print() # Reshaping array in 2 rows and 5 columns one_dim.reshape(2,5) |
The above code will output this result
[ 1 2 3 4 5 6 7 8 9 10]
array([[ 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10]])
Change a two dimensional array into one dimensional
We can use the flatten method to covert a multi dimensional array into 1 dimensional array.
1 2 3 4 5 6 7 8 9 10 11 |
# import numpy library as np import numpy as np # Create an array two_dim = np.array([[1,2,3], [4,5,6]]) print(two_dim) print() # Reshape a multi dimensional array into 1 dimensional array two_dim.flatten() |
The above code will output this result
[[1 2 3]
[4 5 6]]
array([1, 2, 3, 4, 5, 6])