我有一个表,如下所示:
+--------+--------+-----------+------------+
| Binary | Status | Inception | New Status |
+--------+--------+-----------+------------+
| 1 | Raising| 2016 | |
| 1 | Raising| 2017 | |
| 0 | Failed | 2018 | |
| 1 | Closed | 2021 | |
| 1 | Raising| 2020 | |
我一直在按如下方式填充New Status
列:
q = df.query('Binary == 1 and Inception <= 2022 - 3 and Status != "Closed" and Status != "Failed"')
my_query_index = q.index
my_query_index
df.iloc[my_query_index, 3] = "Closed"
df
然而,我想用一种更动态的方式来做这件事,在第一种情况下使用<
,在第二种情况下则使用<=
。在这种情况下,如果今天的日期恰好在今年上半年,我将使用查询
q = df.query('Binary == 1 and Inception < 2022 - 3 and Status != "Closed" and Status != "Failed"')
my_query_index = q.index
my_query_index
df.iloc[my_query_index, 3] = "Closed"
df
如果今天的日期恰好在下半年,请使用
q = df.query('Binary == 1 and Inception <= 2022 - 3 and Status != "Closed" and Status != "Failed"')
my_query_index = q.index
my_query_index
df.iloc[my_query_index, 3] = "Closed"
df
考虑到today = datetime.today().strftime('%Y-%m-%d')
,我想用today
替换Inception
(在代码中(。我不知道如何将这两种情况合并到代码中,也不确定如何将其合并到查询中。
您可以使用str格式进行查询
today = datetime.today().strftime('%Y-%m-%d')
half_year = '2022-06-01'
if today < half_year:
query = 'Binary == 1 and Inception < 2022 - 3 and Status != "Closed" and Status != "Failed"'
else:
query = 'Binary == 1 and Inception <= 2022 - 3 and Status != "Closed" and Status != "Failed"'
然后你的常规代码
q = df.query(query)
my_query_index = q.index
my_query_index
df.iloc[my_query_index, 3] = "Closed"
df