How can data be stored using np.savetxt() in numpy?
To store data using the np.savetxt() function, you need to follow these steps:
- Import the numpy module.
import numpy as np
- Create a numpy array that can store data either as a numpy array or a Python list.
data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
- Use the np.savetxt() function to save data, which requires three mandatory parameters: file name, array, and delimiter to be used. Optional parameters can be used to specify row and column labels, as well as the desired format.
np.savetxt('data.txt', data, delimiter=',', header='col1,col2,col3', fmt='%d')
In this example, we are storing data in a file named “data.txt” with commas as separators. We also specified the column headers as “col1, col2, col3” and the data format as integers.
Please note that if the file name already exists, the np.savetxt() function will overwrite that file.
I hope this helps you!