Getting an array directly from a file

NumPy arrays can also be created directly from the data present in a file.

Let's use an example from the previous chapter:

In: import numpy as np    housing = np.loadtxt('regression-datasets-housing.csv',                         delimiter=',', dtype=float)

NumPy loadtxt, given a filename, delimiter, and dtype, will upload the data to an array, unless the dtype is wrong; for instance, there's a string variable and the required array type is a float, as shown in the following example:

In: np.loadtxt('datasets-uci-iris.csv',delimiter=',',dtype=float)Out: ValueError: could not convert string to float: Iris-setosa  

In this case, a feasible solution could be to be aware of what column is a string (or any other non-numeric format) and ...

Get Python Data Science Essentials - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.