开始使用免费开始使用

使用 pandas 将平面文件导入为 DataFrame(2)

在上一个练习中,您已经能够将平面文件导入到 pandas 的 DataFrame 中。更进一步,您可以直接使用 .to_numpy() 方法获取对应的 numpy 数组。现在,您将用可作为 digits.csv 获取的 MNIST 数据集来练习这一过程。

pd.read_csv() 提供了多个对本练习很有用的参数:

  • nrows 用于指定从文件中读取的行数。例如,nrows=10 只会导入前 10 行。
  • header 接受用作列标签并标记数据起始位置的行号。如果文件不包含表头行,您可以设置 header=Nonepandas 会自动分配从 0 开始的整数列标签(例如 0、1、2、…)。

本练习是课程的一部分

Python 数据导入入门

查看课程

练习说明

  • 使用函数 pd.read_csv() 将文件的「前 5 行」导入为一个 DataFrame,并将结果赋给 data。您需要使用参数 nrowsheader。注意,该文件没有表头行。
  • data 中生成一个 numpy 数组,并赋值给 data_array
  • 执行 print(type(data_array)),打印 data_array 的数据类型。

交互式实操练习

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

# Assign the filename: file
file = 'digits.csv'

# Read the first 5 rows of the file into a DataFrame: data
data = ____(____, ____, ____)

# Build a numpy array from the DataFrame: data_array
data_array = ____

# Print the datatype of data_array to the shell
print(type(data_array))
编辑并运行代码