字符串
在 pandas 中,包含字符串的列表示为 object 类型。
由于您会经常遇到包含字符串的数据,掌握如何处理它们非常重要。
Python 允许您通过 str 访问器调用其内置的字符串处理方法。字符串方法有很多,例如 .upper() 和 .lower()。它们分别将字符串转换为大写和小写。
# 将 'col_a' 转换为小写
df['col_a'].str.lower()
# 将 'col_b' 转换为大写
df['col_b'].str.upper()
本练习是课程的一部分
面向 R 用户的 Python
练习说明
- 在控制台中查看
'sex'和'smoker'两列。 - 将
'sex'列转换为小写。 - 将
'smoker'列转换为大写。 - 再次查看
'sex'和'smoker'两列,确认大小写转换已生效。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Convert sex to lower case
tips____ = tips____
# Convert smoker to upper case
tips____ = tips____
# Print the sex and smoker columns
print(tips[['sex', 'smoker']])