从熊猫数据框中有条件地提取数据

时间:2019-08-20 15:37:00

标签: python pandas dataframe

我有一个简单的DataFrame,看起来像:

enter image description here

          Names
0   Alexi Laiho
1   Jari Maenpaa
2   Kirk Hammett
3   Antti Kokko
4   Yngwie Malmsteen
5   Petri Lindroos

我想检索名称中只有5个以上元音的记录。

为此,我做了函数:

def vowcount(sentence=[]):
    count=0
    vow='aeiouAEIOU'
    for i in sentence:
        for j in i:
            if j in vow:
                count+=1
    return count

如何使用此功能从DataFrame中提取记录? 请帮助我了解如何在此Pandas系列上使用df.apply(map())函数,以及在可能的情况下如何使用列表推导来获得相同的功能。

2 个答案:

答案 0 :(得分:2)

我们可以使用简单的regex语句并使用str.lowerstr.count.query

m = df['Names'].str.lower().str.count(r'[aeiou]')
df = df.query('@m > 5')

或者我们可以使用re.I忽略大小写:

import re

m = df['Names'].str.count(r'[aeiou]', flags = re.I)
df = df.query('@m > 5')

输出

          Names
0   Alexi Laiho
1  Jari Maenpaa

答案 1 :(得分:1)

或者用findall

import re
df[df.Names.str.findall('[aeiou]',flags=re.I).str.len().gt(5)]

          Names
0   Alexi Laiho
1  Jari Maenpaa