pythonadvanced

NumPy Structured Arrays for Records

Use NumPy structured arrays to store heterogeneous record types efficiently without pandas overhead.

python
import numpy as np

dtype = np.dtype([('id', np.int32), ('price', np.float32), ('qty', np.int16), ('label', 'U10')])

records = np.array([(1, 9.99, 3, 'widget'), (2, 24.99, 1, 'gadget'), (3, 4.99, 10, 'bolt')], dtype=dtype)

print(records['price'])
print(records[records['qty'] > 2])

total_revenue = (records['price'] * records['qty']).sum()
print(f'Total revenue: {total_revenue:.2f}')

Use Cases

  • binary record storage
  • memory-efficient arrays
  • C interop

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.