
Python机器学习(八十九)Pandas 整理列名
发布日期:2021-05-14 00:15:15
浏览次数:16
分类:博客文章
本文共 1408 字,大约阅读时间需要 4 分钟。
关于数据集的列名,通常建议最好使用小写字母,删除特殊字符,并用下划线替换空格。有时数据集的列名可能不是很规范,需要整理修改理列名。
获取DataFrame的列名
获取DataFrame的列名,可以使用DataFrame.columns
属性。
movies_df.columns
输出
Index(['Rank', 'Genre', 'Description', 'Director', 'Actors', 'Year', 'Runtime (Minutes)', 'Rating', 'Votes', 'Revenue (Millions)', 'Metascore'], dtype='object')
使用rename方法重命名列名
要重命名列名,可以使用DataFrame.rename()
方法,该方法的参数是包含新旧列名的字典。
movies_df.rename(columns={ 'Runtime (Minutes)': 'Runtime', 'Revenue (Millions)': 'Revenue_millions' }, inplace=True)movies_df.columns
输出
Index(['Rank', 'Genre', 'Description', 'Director', 'Actors', 'Year', 'Runtime', 'Rating', 'Votes', 'Revenue_millions', 'Metascore'], dtype='object')
但是如果我们想把所有的名字都小写呢?除了使用.rename(),我们还可以为列设置一个名称列表,如下所示:
使用columns属性重命名列名
除了rename
方法,columns
属性也可重命名列名。
movies_df.columns = ['rank', 'genre', 'description', 'director', 'actors', 'year', 'runtime', 'rating', 'votes', 'revenue_millions', 'metascore']movies_df.columns
输出
Index(['rank', 'genre', 'description', 'director', 'actors', 'year', 'runtime', 'rating', 'votes', 'revenue_millions', 'metascore'], dtype='object')
上面指定名称的代码过于繁琐,可以使用更简洁的循环:
movies_df.columns = [col.lower() for col in movies_df]movies_df.columns
输出
Index(['rank', 'genre', 'description', 'director', 'actors', 'year', 'runtime', 'rating', 'votes', 'revenue_millions', 'metascore'], dtype='object')
发表评论
最新留言
路过,博主的博客真漂亮。。
[***.116.15.85]2025年04月09日 20时53分17秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
Django ORM操作
2019-03-10
京喜小程序体验评分优化实践
2019-03-10
C#中文转换成拼音
2019-03-10
C++错误笔记
2019-03-10
【无线通信模块】GPRS DTU不稳定和容易掉线原因
2019-03-10
SpringBoot使用RedisTemplate简单操作Redis的五种数据类型
2019-03-10
国标流媒体服务器以ROOT身份运行提示“permission denide”报错解决
2019-03-10
qt中转到槽后如何取消信号与槽关联
2019-03-10
qt问题记录-spin box与double spin box
2019-03-10
移动端事件
2019-03-10
css 图片按比例缩放
2019-03-10
小程序form表单里面buton点击事件失效
2019-03-10
微信小程序placeholder设置自定义样式
2019-03-10
spring-day01
2019-03-10
spring的值注入与组件扫描
2019-03-10
C#跨窗体程序调用方法的具体操作
2019-03-10
C#中创建Android项目
2019-03-10
统计学之变异系数与是非标志
2019-03-10