Categories: NumpyPython

How to create structured arrays in Python

We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental level, click here for more details.

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')

You can also watch videos on our YouTube channel for more understanding of Python programming skills.

wilsonzhang746

Recent Posts

Download R Course source files

Click here to download R Course source files !

2 months ago

Download Python Course source files

Click here to download Python Course Source Files !

2 months ago

How to create a data frame from nested dictionary with Pandas in Python

For online Python training registration, click here ! Pandas provides flexible ways of generating data…

5 months ago

How to delete columns of a data frame in Python

For online Python training registration, click here ! Data frame is the tabular data object…

5 months ago

Using isin() to check membership of a data frame in Python

Click her for course registration ! When a data frame in Python is created via…

5 months ago

How to assign values to Pandas data frame in Python

We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…

5 months ago