python - pandas 按两列过滤(python)

标签 python pandas filter multiple-columns

我有一个包含许多列的 pandas DataFrame (df),其中两列是“Year”和“col_1”

我还有一个总结在列表中的提取标准(Criteria):

[1234,5432,...,54353,654,1234]。

如果满足以下条件,我想提取此 DataFrame 的子集:

((df.Year==1990) & (df.col_1>=Criteria[0])) or

((df.Year==1991) & (df.col_1>=Criteria[1])) or

((df.Year==1992) & (df.col_1>=Criteria[2])) or 

...

((df.Year==2010) & (df.col_1>=Criteria[20])) or

((df.Year==2011) & (df.col_1>=Criteria[21]))

虽然我可以列出这些标准的所有组合,但我想 用一小行代码完成此操作,例如:

df = df[df[['col_1','col_2']].apply(lambda x: f(*x), axis=1)]

(来自 how do you filter pandas dataframes by multiple columns )

请告诉我该怎么做。谢谢。

最佳答案

示例数据帧:

df = pd.DataFrame({'col_1':[2000,1,54353,5],
                   'Year':[1990,1991,1992,1993],
                   'a':range(4)})

print (df)
   col_1  Year  a
0   2000  1990  0
1      1  1991  1
2  54353  1992  2
3      5  1993  3

根据条件和年份组合创建辅助字典:

Criteria = [1234,5432,54353,654,1234]
years = np.arange(1990, 1990 + len(Criteria))
d = dict(zip(years, Criteria))
print (d)
{1990: 1234, 1991: 5432, 1992: 54353, 1993: 654, 1994: 1234}

最后map年份列并按boolean indexing过滤:

df = df[df['col_1'] >= df['Year'].map(d)]
print (df)
   col_1  Year  a
0   2000  1990  0
2  54353  1992  2

详细信息:

print (df['Year'].map(d))
0     1234
1     5432
2    54353
3      654
Name: Year, dtype: int64

print (df['col_1'] >= df['Year'].map(d))

0     True
1    False
2     True
3    False
dtype: bool

关于python - pandas 按两列过滤(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51414814/

相关文章:

python - numpy数组遍历的优化

python - 根据列列表值过滤 pandas 数据框

r - 如何使用 dplyr 通过条件语句过滤分组数据框?

python - 在 iPython 修剪输出中解释 {isinstance}?

hadoop - 需要在Pig脚本中按1分钟过滤记录

google-sheets - 在过滤器公式中使用 Unique

python - 在 Google App Engine Datastore 中按日期过滤

python - Pandas read_csv fillna

python - Django 中的多对一关系

python - 元组元素到 python 中的数据框列