首页 > 解决方案 > 如何在熊猫数据框中过滤小写的行和单词?

问题描述

您好我想知道如何在以下数据框中选择包含小写字母的行:

ID     Name   Note
1      Fin    there IS A dog outside
2      Mik    NOTHING TO DECLARE
3      Lau    no house

我想做的是过滤Note列至少包含一个小写单词的行:

ID     Name   Note
1      Fin    there IS A dog outside
3      Lau    no house

并在列表中收集所有小写单词:my_list=['there','dog','outside','no','house']

我试图过滤行是:

df1=df['Note'].str.lower()

对于在列表中附加单词,我认为我应该首先标记字符串,然后选择小写的所有术语。我对吗?

标签: pythonpandas

解决方案


用于Series.str.contains过滤以下中的至少一个小写字符boolean indexing

df1 = df[df['Note'].str.contains(r'[a-z]')]
print (df1)
   ID Name                    Note
0   1  Fin  there IS A dog outside
2   3  Lau                no house

然后Series.str.extractall提取小写单词:

my_list = df1['Note'].str.extractall(r'(\b[a-z]+\b)')[0].tolist()
print (my_list)
['there', 'dog', 'outside', 'no', 'house']

或者使用拆分句子的列表理解并过滤islower

my_list = [y for x in df1['Note'] for y in x.split() if y.islower()]
print (my_list)
['there', 'dog', 'outside', 'no', 'house']

推荐阅读