numpy.genfromtxt Function
- The numpy.genfromtxt function can be used to load data from a text file. It’s useful for importing data from CSV or other delimited text files into a NumPy array.
- Example: Suppose we have a CSV file named grades.csv that contains the following data:
python
1import numpy as np
2# Example CSV file: grades.csv
3# ID,Math,Science,English,History
4# 1,85,90,88,92
5# 2,78,85,84,80
6# 3,92,88,91,85
7# 4,75,80,78,83
8# 5,88,92,89,90
9# 6,84,87,86,88
10# 7,90,85,88,84
11# 8,76,80,82,78
12
13# Load the CSV file into a NumPy array
14data = np.genfromtxt('grades.csv', delimiter=',', skip_header=1)
15
16# Print the loaded data
17print(data)Output: The data array will contain the following values:
1[[ 1. 85. 90. 88. 92.]
2 [ 2. 78. 85. 84. 80.]
3 [ 3. 92. 88. 91. 85.]
4 [ 4. 75. 80. 78. 83.]
5 [ 5. 88. 92. 89. 90.]
6 [ 6. 84. 87. 86. 88.]
7 [ 7. 90. 85. 88. 84.]
8 [ 8. 76. 80. 82. 78.]]- The documentation for numpy.genfromtxt provides additional information on the function’s parameters and options.