比方说,我有一个数据帧df
,其中包含任意数量的列。例如,说我们有
a b c
0 5 foo 2
1 5 bar 3
2 4 foo 2
3 5 test 1
4 4 bar 7
假设我想要一个类似
的过滤器 df[(df['a'] == 5) & (~df['b'].isin(['foo','bar'])) & (df['c'].isin(range(5)))]
或类似的东西
df[(df['a'] == 5) & (~df['b'].isin(['test','bar'])) | (df['c'].isin(range(5)))]
但是我想要可以轻松插入的东西作为输入,例如:
def filter_df(filter_kwargs, df):
# do the filtering here
我知道如何使用==
运算符,但是我困惑于如何执行更复杂的运算符,例如.isin
和|
。最好的方法是什么?
答案 0 :(得分:1)
这是解决方案的想法
import pandas as pd
df = pd.DataFrame({'a': [5,5,4,5,4], 'b': ['foo','bar','foo','test','bar'],'c': [2,3,2,1,7]})
def helper_function(df, *argv):
x = True
y = "and"
for (i,arg) in enumerate(argv):
if (i % 2 == 1):
y = arg
else:
if (y == "and"):
x = x & df[arg[0]].isin(arg[1])
else:
x = x | df[arg[0]].isin(arg[1])
return df[x]
print(helper_function(df, ['a',[5]],"and",['b',['test','bar']],"and",['c',[0,1,2]]))
答案 1 :(得分:1)
我在这里有三种解决方案。我认为最优雅的是前两个。第三种感觉更像是一种“黑客”,但可以作为其他灵感的来源。
import pandas as pd
df = pd.DataFrame({'a': [5,5,4,5,4], 'b': ['foo','bar','foo','test','bar'],'c': [2,3,2,1,7]})
mask_1 = (df['a'] == 5) & \
(~df['b'].isin(['foo','bar'])) & \
(df['c'].isin(range(5)))
print(df.loc[mask_1])
mask_2 = (df['a'].apply(lambda x: x == 5)) & \
(df['b'].apply(lambda x: x not in ['foo', 'bar'])) & \
(df['c'].apply(lambda x: x in range(5)))
print(df.loc[mask_2])
def filter_df(filter_kwargs, df):
l = len(filter_kwargs)
for i, cond in enumerate(filter_kwargs):
eval_cond = df[cond[0]].apply(lambda x: eval("x " + cond[1]))
if i == 0:
mask = eval_cond
elif i+1 == l:
break
else:
mask = eval('mask' + filter_kwargs[i-1][2] + 'eval_cond')
return df.loc[mask]
# Format for each condition [[column_name, condition, AND_OR],...]
filter_kwargs = [['a', '==5', '&'],['b', 'not in ["foo", "bar"]','&'], ['c', 'in range(5)','|']]
print(filter_df(filter_kwargs,df))
答案 2 :(得分:1)
假设您有此序言
import pandas as pd
df = pd.DataFrame({'a': [5,5,4,5,4], 'b': ['foo','bar','foo','test','bar'],'c': [2,3,2,1,7]})
和此功能
def helper_function(df,d):
x = True
for (i,k) in enumerate(d):
y = getattr(df[k['key']],k['function'])(k['values'])
if k['isnot']:
y = getattr(getattr(y,'__ne__'),'__self__')
if i == 0:
x = y
else:
x = getattr(x,k['left_connector'])(y)
return x
现在您可以创建词典列表
di = [
{
'key': 'a',
'function': 'isin',
'isnot': False,
'values': [5],
'left_connector': "__and__"
},
{
'key': 'b',
'function': 'isin',
'isnot': True,
'values': ['test','bar'],
'left_connector': "__and__"
},
{
'key': 'c',
'function': 'isin',
'isnot': False,
'values': [0,1,2,3],
'left_connector': "__or__"
},
]
并使用此代码进行过滤
df[helper_function(df,di)]
由于仅使用熊猫功能,因此可以保持熊猫的性能。