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

yipeiwu_com6年前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使用pandas和xlsxwriter读写xlsx文件的方法示例

Python使用pandas和xlsxwriter读写xlsx文件的方法示例

python使用pandas和xlsxwriter读写xlsx文件 已有xlsx文件如下: 1. 读取前n行所有数据 # coding: utf-8 import pandas a...

Python实现合并字典的方法

本文实例讲述了Python实现合并字典的方法。分享给大家供大家参考。具体实现方法如下: # 将两个字典合并 #!/usr/bin/python def adddict(dict1,d...

python实现简易动态时钟

本文实例为大家分享了python实现简易动态时钟的具体代码,供大家参考,具体内容如下 from turtle import * from datetime import * #移动到...

python保存字典和读取字典的实例代码

读取一个已经保存了的字典 f = open('dict_th','r') a = f.read() dict_hi = eval(a) f.close() 保存一个字典 dic...

Pandas之ReIndex重新索引的实现

约定: import pandas as pd import numpy as np ReIndex重新索引 reindex()是pandas对象的一个重要方法,其作用是创建一...