开始使用免费开始使用

导入不同数据类型

文件 seaslug.txt

  • 含有由字符串组成的文本表头;
  • 以制表符分隔的。

这些数据记录了在给定时间段内,海蛞蝓幼体完成变态的百分比。您可在此处了解更多。

由于存在表头,如果直接使用 np.loadtxt() 导入,Python 会抛出 ValueError,提示 could not convert string to float。处理方式有两种:第一,您可以将数据类型参数 dtype 设为 str(字符串)。

另一种方式是像之前所示,使用 skiprows 参数跳过首行。

本练习是课程的一部分

Python 数据导入入门

查看课程

练习说明

  • 通过将 file 作为第一个参数,完成第一次对 np.loadtxt() 的调用。
  • 执行 print(data[0]),打印 data 的第一个元素。
  • 完成第二次对 np.loadtxt() 的调用。要导入的 file以制表符分隔的,数据类型为 float,并且需要跳过第一行。
  • 参考上一次的 print() 调用,补全命令以打印 data_float 的第 10 个元素。
  • 执行其余代码以可视化数据。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# 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()
编辑并运行代码