Pandas Dataframe .loc + 更新非唯一日期时间索引?

Pandas Dataframe .loc + update on a non-unique Datetime Index?

有一个带有时间戳 (%Y-%m-%d) 索引的 DataFrame,我希望能够使用 .loc 更新单行,知道日期时间索引值。

我知道索引是非唯一的,这意味着有时我会得到的不仅仅是我想要更新的行。所以我在第二列对 DataFrame 进行了排序,这样我要更新的行将始终是该索引值的最后一行。

有问题的 DataFrame 是一个更大的 DataFrame 的子集副本,不使用 .loc 设置值是行不通的——因此我限制使用 .loc.

我的问题:有没有一种方法可以引用索引值的最后一行并仅基于索引更新它?

显然,仅使用索引值将更新具有该索引的所有行,argmax 似乎不适用于时间戳,虽然我可以暂时重新创建索引以使用我排序的其他列,但我宁愿不这样做如果有直接的方法,请使用这个三步解决方案。

请参阅下面的示例数据帧代码 - 我所追求的是一种仅使用 df['sort']=='d' 更新行的方法,我知道这将是索引的最后一个,仅基于如果可能的话,索引值。

l1 = [datetime.today().date()] * 4
l2 = list(range(1,5))
l3 = ['a','b','c','d']
df= pd.DataFrame(list(zip(l1,l2,l3)),columns=['datetime','value','sort'])
df.set_index('datetime',inplace=True)

df
Out[1317]: 
            value sort
datetime              
2021-10-22      1    a
2021-10-22      2    b
2021-10-22      3    c
2021-10-22      4    d

df.loc[df.index[-1].argmax()]
Traceback (most recent call last):

  File "<ipython-input-1318-e1758b122814>", line 1, in <module>
    df.loc[df.index[-1].argmax()]

AttributeError: 'datetime.date' object has no attribute 'argmax'

df.loc[df.index[-1],'value'] = 5

df
Out[1320]: 
            value sort
datetime              
2021-10-22      5    a
2021-10-22      5    b
2021-10-22      5    c
2021-10-22      5    d

如果要更改数据框最后一行中特定列的值,可以尝试以下代码

df.iloc[-1,0] = 5

-1 -> 最后一行数据框

0 -> 列索引 'value'

基于Udaya's ,我需要的解决方案是:

df.iloc[-1, df.columns.get_loc('value')] = 5