我有一個場景,用戶想要將多個過濾器應(yīng)用于Pandas DataFrame或Series對象。本質(zhì)上,我想有效地將用戶在運(yùn)行時指定的一堆過濾(比較操作)鏈接在一起。過濾器應(yīng)為可加性的(又稱每個過濾器應(yīng)縮小結(jié)果)。我目前正在使用,reindex()但這每次都會創(chuàng)建一個新對象并復(fù)制基礎(chǔ)數(shù)據(jù)(如果我正確理解了文檔)。因此,這在篩選大型Series或DataFrame時可能效率很低。我認(rèn)為使用apply(),map()或類似的方法可能更好。我對Pandas來說還很陌生,所以仍然想盡一切辦法。TL; DR我想采用以下形式的字典,并將每個操作應(yīng)用于給定的Series對象,然后返回“已過濾” Series對象。relops = {'>=': [1], '<=': [1]}長例子我將從當(dāng)前的示例開始,僅過濾單個Series對象。以下是我當(dāng)前正在使用的功能: def apply_relops(series, relops): """ Pass dictionary of relational operators to perform on given series object """ for op, vals in relops.iteritems(): op_func = ops[op] for val in vals: filtered = op_func(series, val) series = series.reindex(series[filtered]) return series用戶向字典提供他們要執(zhí)行的操作:>>> df = pandas.DataFrame({'col1': [0, 1, 2], 'col2': [10, 11, 12]})>>> print df>>> print df col1 col20 0 101 1 112 2 12>>> from operator import le, ge>>> ops ={'>=': ge, '<=': le}>>> apply_relops(df['col1'], {'>=': [1]})col11 12 2Name: col1>>> apply_relops(df['col1'], relops = {'>=': [1], '<=': [1]})col11 1Name: col1同樣,我上述方法的“問題”是,我認(rèn)為在步驟之間存在很多不必要的數(shù)據(jù)復(fù)制。另外,我想對此進(jìn)行擴(kuò)展,以便傳入的字典可以包含要操作的列,并根據(jù)輸入字典過濾整個DataFrame。但是,我假設(shè)該系列的所有工作都可以輕松擴(kuò)展到DataFrame。
3 回答

瀟湘沐
TA貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超6個贊
由于pandas 0.22更新了,因此提供了以下比較選項(xiàng):
gt(大于)
lt(小于)
eq(等于)
ne(不等于)
ge(大于或等于)
還有很多。這些函數(shù)返回布爾數(shù)組。讓我們看看如何使用它們:
# sample data
df = pd.DataFrame({'col1': [0, 1, 2,3,4,5], 'col2': [10, 11, 12,13,14,15]})
# get values from col1 greater than or equals to 1
df.loc[df['col1'].ge(1),'col1']
1 1
2 2
3 3
4 4
5 5
# where co11 values is better 0 and 2
df.loc[df['col1'].between(0,2)]
col1 col2
0 0 10
1 1 11
2 2 12
# where col1 > 1
df.loc[df['col1'].gt(1)]
col1 col2
2 2 12
3 3 13
4 4 14
5 5 15
添加回答
舉報(bào)
0/150
提交
取消