我想通过沿索引的函数过滤熊猫数据框。我似乎找不到执行此操作的内置方法。
因此,从本质上讲,我具有一个函数,该函数可以通过一些任意复杂的方法来确定是否应包含特定索引,在本示例中,我将其称为filter_func
。我希望将以下代码的功能完全应用,但要应用到索引:
new_index = filter(filter_func, df.index)
并且仅包括filter_func
允许的值。索引也可以是任何类型。
这是数据操纵的一个非常重要的因素,因此我想有一种执行此操作的内置方法。
ETA:
我发现按布尔值列表对数据帧进行索引将达到我想要的目的,但仍需要索引空间的两倍才能应用过滤器。因此,我的问题仍然存在,即是否有一种内置的方法不需要占用两倍的空间。
这是一个例子:
import pandas as pd
df = pd.DataFrame({"value":[12,34,2,23,6,23,7,2,35,657,1,324]})
def filter_func(ind, n=0):
if n > 200: return False
if ind % 79 == 0: return True
return filter_func(ind+ind-1, n+1)
new_index = filter(filter_func, df)
我想这样做:
mask = []
for i in df.index:
mask.append(filter_func(i))
df = df[mask]
但是这种方式不会占用索引空间的两倍
答案 0 :(得分:2)
您可以使用map而不是filter,然后进行布尔索引:
df.loc[map(filter_func,df.index)]
value
0 12
4 6
7 2
8 35
答案 1 :(得分:0)
您是否尝试过使用df.apply?
>>> df = pd.DataFrame(np.arange(9).reshape(3, 3), columns=['a', 'b', 'c'])
a b c
0 0 1 2
1 3 4 5
2 6 7 8
df[df.apply(lambda x: x['c']%2 == 0, axis = 1)]
a b c
0 0 1 2
2 6 7 8
您可以根据需要以任何方式自定义lambda函数,如果这不是您想要的,请告诉我。