We know Numpy arrays are data objects that store same type of data in one object. However, this statement is not strictly correct. Numpy provides also availability to create array that allows different data types in it. This kind of array is called structured array. Let us see an example.
#Create a structured array
A1 = np.array([(1, 'Oslo', 0.5, 1+2j),(2, 'Molde', 1.3, 2-2j),
(3, 'Bergen', 0.8, 1+3j)],dtype=('i2, a7, f4, c8'))
A1
#output
array([(1, b'Oslo', 0.5, 1.+2.j), (2, b'Molde', 1.3, 2.-2.j),
(3, b'Bergen', 0.8, 1.+3.j)],
dtype=[('f0', '<i2'), ('f1', 'S7'), ('f2', '<f4'), ('f3', '<c8')])
We have seen, A1 is an array that stores four different data types (integer, string, float, and complex) for its 4 columns. Numpy reads the input data and assigns most reasonable data types for them. Numpy also assign default name for each column, f1, f2, and so on. Both names and data types can be manually specified when calling this statement again.
#create again this structured array, with specified column name and dtype
A1 = np.array([(1, 'Oslo', 0.5, 1+2j),(2, 'Molde', 1.3, 2-2j),
(3, 'Bergen', 0.8, 1+3j)],
dtype=[('index', 'i2'),('City','a6'),('point','f4'),('other','c8')])
A1
#output
array([(1, b'Oslo', 0.5, 1.+2.j), (2, b'Molde', 1.3, 2.-2.j),
(3, b'Bergen', 0.8, 1.+3.j)],
dtype=[('index', '<i2'), ('City', 'S6'), ('point', '<f4'), ('other', '<c8')])
Next we can return column data by indexing its name, result is a one-dimensional array of same data type.
#get the column 'point'
A1['point']
#Output
array([0.5, 1.3, 0.8], dtype=float32)
#get column 'City'
A1['City']
#Output
array([b'Oslo', b'Molde', b'Bergen'], dtype='|S6')
Click here to download Python Course Source Files !
For online Python training registration, click here ! Pandas provides flexible ways of generating data…
For online Python training registration, click here ! Data frame is the tabular data object…
Click her for course registration ! When a data frame in Python is created via…
We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…