Array Attributes and Methods
Learn about NumPy array properties and useful methods
Array Attributes and Methods
Array Attributes
Attributes tell you information about the array.
Shape
Shows dimensions of the array.
import numpy as np
arr_1d = np.array([1, 2, 3, 4, 5])
print("Shape:", arr_1d.shape)
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])
print("Shape:", arr_2d.shape)Output:
Shape: (5,)
Shape: (2, 3)
What shape means:
- (5,) means 1D array with 5 elements
- (2, 3) means 2 rows and 3 columns
Size
Total number of elements.
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print("Size:", arr.size)Output: 6
What size tells you: Total count of all numbers in array.
ndim
Number of dimensions.
import numpy as np
arr_1d = np.array([1, 2, 3])
arr_2d = np.array([[1, 2], [3, 4]])
arr_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print("1D dimensions:", arr_1d.ndim)
print("2D dimensions:", arr_2d.ndim)
print("3D dimensions:", arr_3d.ndim)Output:
1D dimensions: 1
2D dimensions: 2
3D dimensions: 3
dtype
Data type of elements.
import numpy as np
integers = np.array([1, 2, 3])
floats = np.array([1.5, 2.5, 3.5])
print("Integer type:", integers.dtype)
print("Float type:", floats.dtype)Output:
Integer type: int64
Float type: float64
itemsize
Size of each element in bytes.
import numpy as np
arr = np.array([1, 2, 3])
print("Item size:", arr.itemsize, "bytes")Output: Item size: 8 bytes
Why this matters: Helps estimate memory usage for large arrays.
Reshaping Arrays
Change the shape without changing data.
reshape()
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])
reshaped = arr.reshape(2, 3)
print(reshaped)Output:
[[1 2 3]
[4 5 6]]
What reshape does: Converts 1D array (6 elements) to 2D array (2 rows, 3 columns).
Important: Total elements must match. 6 elements = 2×3 = 6.
reshape with -1
Let NumPy calculate one dimension.
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
reshaped = arr.reshape(2, -1)
print(reshaped)Output:
[[1 2 3 4]
[5 6 7 8]]
What -1 does: NumPy figures out it needs 4 columns (8 elements ÷ 2 rows = 4).
flatten()
Convert any array to 1D.
import numpy as np
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])
flattened = arr_2d.flatten()
print(flattened)Output: [1 2 3 4 5 6]
ravel()
Similar to flatten but faster.
import numpy as np
arr_2d = np.array([[1, 2], [3, 4]])
raveled = arr_2d.ravel()
print(raveled)Output: [1 2 3 4]
Difference: flatten() creates copy, ravel() creates view (usually faster).
Statistical Methods
Calculate statistics on arrays.
sum()
import numpy as np
numbers = np.array([10, 20, 30, 40])
total = numbers.sum()
print("Sum:", total)Output: Sum: 100
mean()
import numpy as np
scores = np.array([85, 90, 78, 92])
average = scores.mean()
print("Average:", average)Output: Average: 86.25
min() and max()
import numpy as np
temperatures = np.array([72, 68, 75, 70, 73])
print("Lowest:", temperatures.min())
print("Highest:", temperatures.max())Output:
Lowest: 68
Highest: 75
std() and var()
import numpy as np
data = np.array([2, 4, 4, 4, 5, 5, 7, 9])
print("Standard deviation:", data.std())
print("Variance:", data.var())What these measure:
- std: How spread out numbers are
- var: Square of standard deviation
Finding Positions
argmin() and argmax()
Find position of minimum and maximum.
import numpy as np
prices = np.array([45, 32, 67, 28, 51])
print("Cheapest at index:", prices.argmin())
print("Most expensive at index:", prices.argmax())
print("Cheapest price:", prices[prices.argmin()])
print("Highest price:", prices[prices.argmax()])Output:
Cheapest at index: 3
Most expensive at index: 2
Cheapest price: 28
Highest price: 67
Sorting
sort()
import numpy as np
numbers = np.array([5, 2, 8, 1, 9])
numbers.sort()
print(numbers)Output: [1 2 5 8 9]
Warning: This changes the original array!
np.sort()
Returns sorted copy without changing original.
import numpy as np
numbers = np.array([5, 2, 8, 1, 9])
sorted_numbers = np.sort(numbers)
print("Sorted:", sorted_numbers)
print("Original:", numbers)Output:
Sorted: [1 2 5 8 9]
Original: [5 2 8 1 9]
Copying Arrays
copy()
Create independent copy.
import numpy as np
original = np.array([1, 2, 3])
copy = original.copy()
copy[0] = 99
print("Original:", original)
print("Copy:", copy)Output:
Original: [1 2 3]
Copy: [99 2 3]
Without copy:
import numpy as np
original = np.array([1, 2, 3])
reference = original
reference[0] = 99
print("Original:", original)
print("Reference:", reference)Output:
Original: [99 2 3]
Reference: [99 2 3]
Both changed! They point to same data.
Practice Example
The scenario: Analyze student test scores.
import numpy as np
scores = np.array([78, 85, 92, 88, 76, 95, 82, 90, 87, 91])
print("Score Analysis")
print("=" * 40)
print("Number of students:", scores.size)
print("Data type:", scores.dtype)
print("Dimensions:", scores.ndim)
print()
print("Statistics:")
print("Average score:", scores.mean())
print("Highest score:", scores.max())
print("Lowest score:", scores.min())
print("Standard deviation:", round(scores.std(), 2))
print()
print("Top student at position:", scores.argmax())
print("Lowest student at position:", scores.argmin())
print()
sorted_scores = np.sort(scores)
print("Scores (sorted):", sorted_scores)
print()
reshaped = scores.reshape(2, 5)
print("Scores in 2 groups:")
print(reshaped)
print()
above_85 = scores[scores > 85]
print("Scores above 85:", above_85)
print("Count above 85:", above_85.size)What this analyzes:
- Basic array information
- Statistical measures
- Best and worst performers
- Sorted view of scores
- Grouping students
- Filtering high scorers
Converting Data Types
astype()
import numpy as np
floats = np.array([1.7, 2.3, 3.9])
integers = floats.astype(int)
print("Floats:", floats)
print("Integers:", integers)Output:
Floats: [1.7 2.3 3.9]
Integers: [1 2 3]
Warning: Decimal parts are lost, not rounded!
Transposing Arrays
Swap rows and columns.
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print("Original:")
print(matrix)
print("Shape:", matrix.shape)
transposed = matrix.T
print("Transposed:")
print(transposed)
print("Shape:", transposed.shape)Output:
Original:
[[1 2 3]
[4 5 6]]
Shape: (2, 3)
Transposed:
[[1 4]
[2 5]
[3 6]]
Shape: (3, 2)
Key Points to Remember
Use .shape to check dimensions, .size for total elements, .dtype for data type.
reshape() changes shape but total elements must stay same. Use -1 to let NumPy calculate one dimension.
Statistical methods: sum(), mean(), min(), max(), std(). Work on entire array or specific axis.
argmin() and argmax() return position (index), not the value itself.
Use .copy() to create independent copy. Without it, you get reference to same data.
Common Mistakes
Mistake 1: reshape with wrong total
arr = np.array([1, 2, 3, 4, 5])
arr.reshape(2, 3) # Error! 5 elements can't fit 2×3=6Mistake 2: Forgetting copy
arr1 = np.array([1, 2, 3])
arr2 = arr1 # Not a copy!
arr2[0] = 99 # Changes both!Mistake 3: In-place sort
numbers.sort() # Changes original
sorted_nums = np.sort(numbers) # Keeps originalMistake 4: Wrong axis
matrix.sum() # Sums everything
matrix.sum(axis=0) # Sums each column
matrix.sum(axis=1) # Sums each rowWhat's Next?
You now know array attributes and methods. Next, you'll learn about array indexing and slicing - how to access and extract specific parts of arrays.