Importing different datatypes
The file seaslug.txt
- has a text header, consisting of strings
- is tab-delimited.
This data consists of the percentage of sea slug larvae that had metamorphosed in a given time period. Read more here.
Due to the header, if you tried to import it as-is using
np.loadtxt()
, Python would throw you a ValueError
and tell
you that it could not convert string to float
. There are
two ways to deal with this: firstly, you can set the data type
argument dtype
equal to str
(for string).
Alternatively, you can skip the first row as we have seen before,
using the skiprows
argument.
This exercise is part of the course
Introduction to Importing Data in Python
Exercise instructions
- Complete the first call to
np.loadtxt()
by passingfile
as the first argument. - Execute
print(data[0])
to print the first element ofdata
. - Complete the second call to
np.loadtxt()
. Thefile
you're importing is tab-delimited, the datatype isfloat
, and you want to skip the first row. - Print the 10th element of
data_float
by completing theprint()
command. Be guided by the previousprint()
call. - Execute the rest of the code to visualize the data.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Assign filename: file
file = 'seaslug.txt'
# Import file: data
data = np.loadtxt(____, delimiter='\t', dtype=str)
# Print the first element of data
print(data[0])
# Import file as floats and skip the first row: data_float
data_float = np.loadtxt(____, delimiter='____', dtype=____, skiprows=____)
# Print the 10th element of data_float
print(____)
# Plot a scatterplot of the data
plt.scatter(data_float[:, 0], data_float[:, 1])
plt.xlabel('time (min.)')
plt.ylabel('percentage of larvae')
plt.show()