您可以使用 lambda 在 Pandas 中执行高级过滤。
假设:
- 所有月份和年份都是整数
- 约束在
list of dict 类型中
如果数据类型不同,您可以修改以下几行以适应您的问题。
生成随机数据填充数据框
In [1]: from random import randint
In [2]: months = [randint(1, 12) for x in range(10)]
In [3]: years = [randint(2000, 2020) for x in range(10)]
In [4]: months
Out[4]: [12, 3, 7, 6, 10, 10, 11, 9, 9, 10]
In [5]: years
Out[5]: [2017, 2016, 2001, 2004, 2015, 2013, 2001, 2020, 2013, 2016]
In [6]: import pandas as pd
In [7]: df = pd.DataFrame()
In [8]: df['Month'] = months
In [9]: df['Year'] = years
2。使用给定的list of dict 并将其转换为list of tuple 以便于编码
(注意:一旦你理解了我想要完成的事情,你可以随意改变你的约束。)
In [10]: filterDict = [{1: 2003}, {2: 2008}, {3: 2011}, {4: 2012}, {5: 2008}, {6: 2008}, {7: 2002}, {8: 2006}, {9: 2005}, {3: 2016}, {6: 2004}, {12: 2001}]
In [11]: filterList = [d.items()[0] for d in filterDict]
3.使用lambda 过滤数据框
In [12]: df[df.apply(lambda x: (x['Month'],x['Year']) in filterList, axis=1)]
Out[12]:
Month Year
1 3 2016
3 6 2004
过滤前的原始数据供您参考:
In [13]: df
Out[13]:
Month Year
0 12 2017
1 3 2016
2 7 2001
3 6 2004
4 10 2015
5 10 2013
6 11 2001
7 9 2020
8 9 2013
9 10 2016