利用pandas对一列/多列进行数据区间筛选

  • 前言
    如果不整活,那就是浪费生命

下面这个表,如果你想筛选出age大于等于18,小于等于30的行:

在这里插入图片描述

如果在mysql中整这种活很容易,用个where就可以了

在pandas中也有相当于where作用的语法,loc

筛选18<=age<=30的数据:

import pandas as pd

stu = pd.read_csv("data/student.csv", index_col='id')

# 留下18<=年龄<=30
def age_18_to30(a):
    return 18 <= a <= 30

# 留下 85<=score
def level_a(s):
    return 85 <= s

# 使用loc会生成一个新的series
stu = stu.loc[stu['age'].apply(age_18_to30)]
# 或者用下lambda表达式:
# stu = stu.loc[stu['age'].apply(lambda a:18<=a<=30)]

print(stu)

结果:

在这里插入图片描述

而此时再加一个筛选条件:

age大于等于18,小于等于30且分数大于等于85:

代码:


import pandas as pd

stu = pd.read_csv("data/student.csv", index_col='id')


# 留下18<=年龄<=30
def age_18_to30(a):
    return 18 <= a <= 30


# 留下 85<=score
def level_a(s):
    return 85 <= s

stu = stu.loc[stu['age'].apply(age_18_to30)].loc[stu['score'].apply(level_a)]

print(stu)

结果:

在这里插入图片描述

其中,获取莫一列,我们一直使用的是stu['age'],这个还可以写为:stu.age

然后就整活成功了

文件:F:\Project\python\src\WangYiYun\DataAnalysis\19_.py

完整代码:

# @DATE : 2021-1-2
# @TIME : 16:13
# @USER : kirin
import pandas as pd

stu = pd.read_csv("data/student.csv", index_col='id')

# 留下18<=年龄<=30
def age_18_to30(a):
    return 18 <= a <= 30

# 留下 85<=score
def level_a(s):
    return 85 <= s

# 使用loc会生成一个新的series
# stu = stu.loc[stu['age'].apply(age_18_to30)]
stu = stu.loc[stu['age'].apply(age_18_to30)].loc[stu['score'].apply(level_a)]
# 或者不使用 stu['age'] :
# stu = stu.loc[stu.age.apply(age_18_to30)].loc[stu.score.apply(level_a)]

# 使用lambda表达式:
# stu = stu.loc[stu.age.apply(lambda a: 18 <= a <= 30)].loc[stu.score.apply(lambda s: 85 <= s)]

# 代码太长回个车:(空格+反斜线+回车)
# stu = stu.loc[stu.age.apply(lambda a: 18 <= a <= 30)]. \
#     loc[stu.score.apply(lambda s: 85 <= s)]

print(stu)
  • 3
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无名之辈无名之辈

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值