How do I change a pandas row value, for a certain column, for a certrain date (datetimeindex) in a dataframe?

Question:

I have a pd like this:

DATE          delivery
2020-01-01     1
2020-01-01    11
2020-01-01    10
2020-01-01     9
2020-01-01     8
              ..
2023-03-02     5
2023-03-02     4
2023-03-02     3
2023-03-02     2
2023-03-02    11

Index is DateTimeIndex but not unique. I have a list (date_adj) of a few dates from the df, and I want to change the ‘delivery’ column for those dates. I tried:

for i in date_adj:
    for x in range(1,11):
        df.loc[((df.index == i) & (df.delivery == x)), 
                     [df.delivery]] = (df.delivery + 1)

I get the following error message: KeyError: "None of [Index([(1, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 6, 9, 8, 7, 5, 4, 3, 2, 10, 11, 4, 1, 5, 6, 7, 8, 1, 9, 10, 11, 3, 2, 2, 7, 3, 4, 5, 6, 8, 9, 10, 11, 1, 1, 3, 4, 5, 6, 7, 8, 9, 10, 2, 11, 2, 4, 5, 6, 7, 8, 9, 10, 11, 3, 11, 10, 9, 8, 7, 2, 5, 4, 3, 1, 2, 6, 1, 3, 7, 4, 5, 6, 8, 10, 11, 9, 4, 9, 8, 7, 6, 5, 4, 3, 1, 5, 11, 9, …)], dtype=’object’)] are in the [columns]"

For illustrational purposes, I would like the result to look like this, given the date in the list is ‘2023-03-02’:

DATE          delivery
2020-01-01     1
2020-01-01    11
2020-01-01    10
2020-01-01     9
2020-01-01     8
              ..
2023-03-02     6
2023-03-02     5
2023-03-02     4
2023-03-02     3
2023-03-02    12

Help would be very appreciated.

Asked By: cJc

||

Answers:

It’s not fully clear, but I think that you want:

date_adj = ['2020-01-01', '2020-01-02']

df.loc[df['DATE'].isin(date_adj) & df['delivery'].between(1, 11), 'delivery'] += 1

Output:

         DATE  delivery
0  2020-01-01         2
1  2020-01-01        12
2  2020-01-01        11
3  2020-01-01        10
4  2020-01-01         9
5  2023-03-02         5
6  2023-03-02         4
7  2023-03-02         3
8  2023-03-02         2
9  2023-03-02        11
Answered By: mozway
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.