add column in pandas dataframe by condition

I have a list

sample_dates = ["10/07/2021","11/07/2021","12/07/2021","13/07/2021",
                "14/07/2021","15/07/2021","16/07/2021","17/07/2021",
                "18/07/2021","19/07/2021","20/07/2021","21/07/2021",
                "22/07/2021"]

and i have a dataframe like below

Truckid   Tripid
  1          1
  1          1
  1          1
  1          2
  1          2
  1          3
  1          3
  1          3
  1          4
  1          4
  1          4
  1          5
  1          5
  1          5
  2          1
  2          1
  2          2
  2          2
  2          2
  2          3
  2          3

I want to add the Date column in a way like whenever trip_id changes the number, the date should move to next element

I want result to be like below

Truckid   Tripid   Date  
  1          1     10/07/2021
  1          1     10/07/2021 
  1          1     10/07/2021
  1          2     11/07/2021
  1          2     11/07/2021
  1          3     12/07/2021
  1          3     12/07/2021
  1          3     12/07/2021
  1          4     13/07/2021
  1          4     13/07/2021
  1          4     13/07/2021
  1          5     14/07/2021
  1          5     14/07/2021 
  1          5     14/07/2021 
  2          1     15/07/2021 
  2          1     15/07/2021
  2          2     16/07/2021
  2          2     16/07/2021
  2          2     16/07/2021
  2          3     17/07/2021
  2          3     17/07/2021

>Solution :

You can compute the group number (from 0 to n) using GroupBy.ngroup, and map the value to your list indices (using a temporary dictionary):

df['Date'] = (df
              .groupby(['Truckid', 'Tripid']).ngroup() # get group ID
              .map(dict(enumerate(sample_dates)))      # match to items in order
             )

output:

    Truckid  Tripid        Date
0         1       1  10/07/2021
1         1       1  10/07/2021
2         1       1  10/07/2021
3         1       2  11/07/2021
4         1       2  11/07/2021
5         1       3  12/07/2021
6         1       3  12/07/2021
7         1       3  12/07/2021
8         1       4  13/07/2021
9         1       4  13/07/2021
10        1       4  13/07/2021
11        1       5  14/07/2021
12        1       5  14/07/2021
13        1       5  14/07/2021
14        2       1  15/07/2021
15        2       1  15/07/2021
16        2       2  16/07/2021
17        2       2  16/07/2021
18        2       2  16/07/2021
19        2       3  17/07/2021
20        2       3  17/07/2021

Leave a Reply