Closed
Description
Code Sample, a copy-pastable example if possible
# Function
def _filter(self, func):
return self[list(map(func, self))]
# Set the attribute
setattr(pd.Index, "filter", _filter)
index = pd.Index(["iris_1", "notiris_1", "iris_2", "other_thing"])
# New way
func = lambda x:x.startswith("iris")
print("New way:", index.filter(func))
# Old way
print("Old way:", index[index.map(func)])
# New way: Index(['iris_1', 'iris_2'], dtype='object')
# Old way: Index(['iris_1', 'iris_2'], dtype='object')
# Set the attribute
setattr(pd.Series, "filter", _filter)
series = pd.Series(list("imagine_more_complex_stuff_here_instead"))
# New way
func = lambda x:x in ["o", "_"]
print("New way:", series.filter(func))
# Old way
print("Old way:", series[series.map(func)])
# New way: 7 _
# 9 o
# 12 _
# 14 o
# 20 _
# 26 _
# 31 _
# dtype: object
# Old way: 7 _
# 9 o
# 12 _
# 14 o
# 20 _
# 26 _
# 31 _
# dtype: object
Problem description
II always find myself writing really verbose code to filter my pandas indices or series. I love the map method and would like to extend this concept to include filter
.