自定义导入电子表格
本练习将解析您的电子表格,并使用额外参数来跳过行、重命名列,以及仅选择特定列。
电子表格 'battledeath.xlsx' 已作为 xls 加载。
与之前一样,您将使用 parse() 方法。但这一次,您会额外加入 skiprows、names 和 usecols 参数。它们分别用于跳过行、指定列名,以及指明要解析的列。以上各参数都可以赋值为列表,列表中包含具体的行号、字符串和列号(视情况而定)。
本练习是课程的一部分
Python 数据导入入门
练习说明
- 按索引解析第一个工作表。解析时跳过首行数据,并使用参数
names将列命名为'Country'和'AAM due to War (2002)'。传给skiprows和names的值都需要是list类型。 - 按索引解析第二个工作表。解析时仅使用
usecols参数解析第一列,同时跳过首行,并将该列重命名为'Country'。传给usecols的参数也需要是list类型。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Parse the first sheet and rename the columns: df1
df1 = xls.parse(____, skiprows=____, names=____)
# Print the head of the DataFrame df1
print(df1.head())
# Parse the first column of the second sheet and rename the column: df2
df2 = xls.parse(____, usecols=____, skiprows=____, names=____)
# Print the head of the DataFrame df2
print(df2.head())