Write a function reshaped_by_col(nums, col) which takes a Python list nums, and an integer value for columns that reshapes the 1D nums into col number of columns. Finally, returns the reshaped numpy array. If the shape cannot be reshaped, return None (you can do this without catching exceptions).
For example:
Test | Result |
---|---|
nums = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] col = 2 print(reshaped_by_col(nums, col)) |
[[ 10 20] [ 30 40] [ 50 60] [ 70 80] [ 90 100]] |
import numpy as np
def reshaped_by_col(nums,col):
nums=np.array(nums)
# finding the length of nums array
length=len(nums)
# if length is dicisible by col than answer is possible else answer will be None
if length%col==0:
# finding no of rows for the reshaped array
row_size=length//col
# reshaping matrix with reshape function of numpy
reshaped=nums.reshape(row_size,col)
return reshaped
else:
return None
# array which needs to be reshaped
nums=[10,20,30,40,50,60,70,80,90,100]
# number of columns in reshaped 2 -D array
col=2
# calling hte reshaped funciton and printing the reshaped array
print(reshaped_by_col(nums, col))
Get Answers For Free
Most questions answered within 1 hours.