gpt4 book ai didi

python - Pandas:条件语句未按预期工作

转载 作者:行者123 更新时间:2023-11-30 22:41:33 24 4
gpt4 key购买 nike

鉴于以下虚拟数据,我的目标是确定一名员工在 2014 年底是否受雇,并为此返回一个新的 bool 列。

name    hire_date    termination_date   grade_2014
James 1999-01-01 NaT 10.0
Amara 2015-12-07 NaT NaN
Haj 2012-08-13 2016-04-04 9.0
Bill 1999-01-12 2014-02-04 7.0

我编写了以下列表组合来实现此目的。

from itertools import izip
df['active_end_2014'] = ['true' if
(hire < pd.Timestamp(2014, 12, 31) and termination == pd.NaT) |
(termination > pd.Timestamp(2015, 1, 1) and grade_2014 != np.nan)
else 'false' for grade_2014, termination, hire in izip(df['grade_2014'],
df['termination_date'],
df['hire_date'])]

为所有员工返回正确的 bool 值,但 James 得到“错误”。

df[df['name'] == 'James']

name    hire_date   termination_date    grade_2014  active_end_2014
James 1999-01-01 NaT 10.0 false

为什么他没有被指定为“true”,因为他肯定满足这个条件:

hire < pd.Timestamp(2014, 12, 31) and termination == pd.NaT

这是括号的问题还是 pd.Nat 的选择问题?或者也许我如何更广泛地构建列表组合?

最佳答案

你应该使用boolean indexing正确地:

In [81]: df['active_end_2014'] = \
...: ((df.hire_date < '2014-12-31') & df.termination_date.isnull()) | \
...: ((df.termination_date > '2015-01-01') & df.grade_2014.notnull())

In [82]: df
Out[82]:
name hire_date termination_date grade_2014 active_end_2014
0 James 1999-01-01 NaT 10.0 True
1 Amara 2015-12-07 NaT NaN False
2 Haj 2012-08-13 2016-04-04 9.0 True
3 Bill 1999-01-12 2014-02-04 7.0 False

关于python - Pandas:条件语句未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42483112/

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