Aan de slagGa gratis aan de slag

Customizing your NumPy import

What if there are rows, such as a header, that you don't want to import? What if your file has a delimiter other than a comma? What if you only wish to import particular columns?

There are a number of arguments that np.loadtxt() takes that you'll find useful:

  • delimiter changes the delimiter that loadtxt() is expecting.
    • You can use ',' for comma-delimited.
    • You can use '\t' for tab-delimited.
  • skiprows allows you to specify how many rows (not indices) you wish to skip.
  • usecols takes a list of the indices of the columns you wish to keep.

The file that you'll be importing, digits_header.txt, has a header and is tab-delimited.

Deze oefening maakt deel uit van de cursus

Introduction to Importing Data in Python

Cursus bekijken

Oefeninstructies

  • Complete the arguments of np.loadtxt(): the file you're importing is tab-delimited, you want to skip the first row and you only want to import the first and third columns.
  • Complete the argument of the print() call in order to print the entire array that you just imported.

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

# Import numpy
import numpy as np

# Assign the filename: file
file = 'digits_header.txt'

# Load the data: data
data = np.loadtxt(____, delimiter='____', skiprows=____, usecols=[____])

# Print data
print(____)
Code bewerken en uitvoeren