分类
Pandas 提供了 category 数据类型,与 R 中的 factor 类似。
您可以通过在 .astype() 方法中传入 'category' 将某一列转换为分类数据类型。
将某列转换为分类后,您可以通过 .cat 访问器并调用 .categories 属性来查看各个类别(在 R 中称为"levels")。
分类值的另一个用例是当您希望在数据中保留顺序时。
例如,直觉上 "low" 应该在 "high" 之前。您可以使用 reorder_categories() 为某列提供顺序。
# 重新排列分类水平
df['column_name'].cat.reorder_categories(['low', 'high'], ordered=True)
本练习是课程的一部分
面向 R 用户的 Python
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Convert the type of time column
tips['time'] = ____
# Use the cat accessor to print the categories in the time column
print(____)