python多条件筛选数据-Python实现多条件筛选目标数据功能【测试可用】

本文实例讲述了Python实现多条件筛选目标数据功能。分享给大家供大家参考,具体如下:

python中提供了一些数据过滤功能,可以使用内建函数,也可以使用循环语句来判断,或者使用pandas库,当然在有些情况下使用pandas是为了提高工作效率。举例如下:

a = [("chic", "JJ"), ("although", "IN"), ("menu", "JJ"), ("items", "NNS"), ("doesnt", "JJ"),

("scream", "NN"), ("french", "JJ"), ("cuisine", "NN")]

这里的a为一个list,列表中还有元组。每一个元组由单词和其词性组成,我们要筛选词性为JJ何NN的单词。可以有三种写法:

第一种,使用内建函数filter:

# -*- coding:utf-8 -*-

#!python3

a = [("chic", "JJ"), ("although", "IN"), ("menu", "JJ"), ("items", "NNS"), ("doesnt", "JJ"),

("scream", "NN"), ("french", "JJ"), ("cuisine", "NN")]

def filt_nn(data_text):

nn_data = filter(lambda x: x[1] == "NN"or x[1] == "JJ", data_text)

# print(list(nn_data))

return list(nn_data)

print(filt_nn(a))

运行结果:

[("chic", "JJ"), ("menu", "JJ"), ("doesnt", "JJ"), ("scream", "NN"), ("french", "JJ"), ("cuisine", "NN")]

第二种,使用pandas包:

# -*- coding:utf-8 -*-

#!python3

import pandas as pd

a = [("chic", "JJ"), ("although", "IN"), ("menu", "JJ"), ("items", "NNS"), ("doesnt", "JJ"),

("scream", "NN"), ("french", "JJ"), ("cuisine", "NN")]

data = pd.DataFrame(a, columns=["word", "ps"])

print(data[data.ps.isin(["JJ", "NN"])].word)

运行结果:

0 chic

2 menu

4 doesnt

5 scream

6 french

7 cuisine

Name: word, dtype: object

第三种,使用循环:

# -*- coding:utf-8 -*-

#!python3

a = [("chic", "JJ"), ("although", "IN"), ("menu", "JJ"), ("items", "NNS"), ("doesnt", "JJ"),

("scream", "NN"), ("french", "JJ"), ("cuisine", "NN")]

absd = []

for i in a:

if i[1] == "NN" or i[1] == "JJ":

absd.append(i[0])

print(absd)

得到的结果都相同,如下:

["chic", "menu", "doesnt", "scream", "french", "cuisine"]

虽然结果相同,但是推荐第一、二种方法,因为这两个方法速度更快。

更多关于Python相关内容可查看本站专题:《Python列表(list)操作技巧总结》、《Python字符串操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。

本文标题: Python实现多条件筛选目标数据功能【测试可用】

本文地址: http://www.cppcns.com/jiaoben/python/230156.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值