1.Python filter() 函數(shù)
- filter() 函數(shù)用于過濾序列,過濾掉不符合條件的元素,返回一個(gè)迭代器對(duì)象,如果要轉(zhuǎn)換為列表,可以使用 list() 來轉(zhuǎn)換
filter(function, iterable)`
# function -- 判斷函數(shù)。對(duì)每個(gè)元素進(jìn)行判斷,返回 True或 False
# iterable -- 可迭代對(duì)象。
# 過濾處列表中的奇數(shù)
def is_odd(n):
return n % 2 == 1
tmplist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
newlist = list(tmplist)
print(newlist)
輸出結(jié)果 :
[1, 3, 5, 7, 9]
2.Pandas中的DataFrame.filter()
DataFrame.filter(items=None, like=None, regex=None, axis=None)
#items對(duì)行/列進(jìn)行篩選
#regex表示用正則進(jìn)行匹配
#like進(jìn)行篩選
#axis=0表示對(duì)行操作,axis=1表示對(duì)列操作
#items對(duì)列進(jìn)行篩選
df.filter(items=['one', 'three'])
one three
teacher 1 3
student 4 6
#regex表示用正則進(jìn)行匹配
df.filter(regex='e$', axis=1)
one three
teacher 1 3
student 4 6
#like進(jìn)行篩選
df.filter(like='ent', axis=0)
one two three
student 4 5 6
總結(jié)
- python filter是過濾掉滿足某個(gè)條件的
- pandas filter是過濾出滿足某個(gè)條件的
本文使用 文章同步助手 同步