Pandas学习之路【3】
新增列的一些操作
1.新增一个列,直接给列赋值
1 2 | # 取所有行,新增的列为new_col df.loc[:, 'new_col' ] = 100 |
2.使用df.apply方法给新增的列赋值
1 2 3 4 5 6 7 8 9 10 | def get_wendu_type(x): if x[ 'bWendu' ]>33: return '高温' if x[ 'bWendu' ]<-10: return '低温' return '常温' # apply通过调用get_wendu_type函数,会得到一个series, 然后把这个series赋值给新增的列new_col_wendu_type # 如果axis=0的话,就是赋值给行 df.loc[:, 'new_col_wendu_type' ] = df.apply(get_wendu_type, axis=1) |
1 2 | # 计数统计 df[ 'new_col_wendu_type' ].value_counts() |
3.使用df.assign方法新增列,并赋值
1 2 3 4 5 6 7 | # yWendu_huashidu,bWendu_huashidu为新增的列名 # 通过函数给列赋值 # 例如:将温度转化为华氏度 df.assign( yWendu_huashidu = lambda x: x[ 'yWendu' ] * 9 / 5 + 32, bWendu_huashidu = lambda x: x[ 'yWendu' ] * 9 / 5 + 32 ) |
4.先按条件筛选出数据,然后对于这些数据在新列上赋值
1 2 3 4 5 6 | # 先创建一个空的列温度类型:wendu_type df[ 'wendu_type' ] = '' # 如果最高温度 - 最低温度 大于10 则将wendu_type列赋值为 温差大, 反之为 温差小 df.loc[df[ 'bWendu' ] - df[ 'yWendu' ] > 10, 'wendu_type' ] = '温差大' df.loc[df[ 'bWendu' ] - df[ 'yWendu' ] <= 10, 'wendu_type' ] = '温差小' |
1 2 | # 计数统计 df[ 'wendu_type' ].value_counts() |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现