比方说,我有一个pandas数据框,我将需要从中重复查询行的子集。我想将其包装在一个函数中。查询将有所不同,将查询任意数量的列。每列的运算符将始终相同。我正在考虑这样的事情:
df = pd.DataFrame({'A': list('aabbccddeeff'), 'B': list('aaaabbbbcccc'),
'C': np.random.randint(5, size=12),
'D': np.random.randint(9, size=12)})
def query_df(df, **kwds):
a_val = kwds.get('a', None)
b_val = kwds.get('b', None)
c_val = kwds.get('c', None)
d_val = kwds.get('d', None)
query = 'A in {0} and B == {1} and C > {2} and D < {3}'.format(a_val, b_val, c_val, d_val)
return df.query(query)
query_dict = {'a':['a', 'b', 'c', 'd'], 'b':'a', 'c':0, 'd':8}
print(query_df(df, **query_dict))
A B C D
1 a a 1 6
尽管这可行,但不允许查询指向仅列A和列C。所有列都硬编码到查询字符串中!我该如何使其更加灵活,例如以下方法也可以:
query_df(df, {'a':['a', 'b', 'c', 'd'], 'b':'a'})
query_df(df, {'b':'a', 'c':6})
query_df(df, {'d':4})
谢谢!
答案 0 :(得分:1)
让您了解如何实现此目标:
import pandas as pd
import numpy as np
df = pd.DataFrame({'A': list('aabbccddeeff'), 'B': list('aaaabbbbcccc'),
'C': np.random.randint(5, size=12),
'D': np.random.randint(9, size=12)})
print(df)
def query_df(df, dicti):
d = {
'a' : 'A in %s' % dicti.get('a'),
'b' : 'B == %s' % dicti.get('b'),
'c' : 'C > %s' % dicti.get('c') ,
'd' : 'D < %s' % dicti.get('d')
}
q = []
for i, j in d.items():
if i in dicti.keys():
q.append(j)
q.append(' and ')
q = q[:len(q)-1]
query = ''.join(q)
print(query)
return df.query(query)
#di = {'a':['a', 'b', 'c', 'd'], 'b':'"a"', 'c':0, 'd':8}
#di = {'b':'"a"', 'c':6}
#di = {'d':4}
di = {'a':['a', 'b', 'c', 'd'], 'b':'"a"'}
print(query_df(df, di))
您可能会注意到,我不得不对'b'键('b':'“ a”')使用双引号。