gpt4 book ai didi

python - pandas 按两列过滤(python)

转载 作者:行者123 更新时间:2023-12-01 09:13:54 24 4
gpt4 key购买 nike

我有一个包含许多列的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com