Writing CSV files with NumPy and pandas
In the previous chapters, we learned about reading CSV files. Writing CSV files is just as straightforward, but uses different functions and methods. Let's first generate some data to be stored in the CSV format. Generate a 3 x 4 NumPy array after seeding the random generator in the following code snippet.
Set one of the array values to NaN
:
np.random.seed(42) a = np.random.randn(3, 4) a[2][2] = np.nan print a
This code will print the array as follows:
[[ 0.49671415 -0.1382643 0.64768854 1.52302986] [-0.23415337 -0.23413696 1.57921282 0.76743473] [-0.46947439 0.54256004 nan -0.46572975]]
The NumPy savetxt()
function is the counterpart of the NumPy loadtxt()
function and can save arrays in delimited file formats such as CSV. Save the array we created with the following function call:
np.savetxt('np.csv', a, fmt='%.2f', delimiter=',', header=" #1, #2, #3, #4")
In the preceding function call, we specified the name of the file to be saved...