How to reverse the column value based on multiple conditions in pandas dataframe?

Viewed 215

I want to reverse the particular column values based on multiple conditions. I have a time-series dataset containing the (date, DeviceID, Value) column.

Input data:

|      date        || DeviceID  |   | Value |
| ---------------- || --------- |   | ----- |
| 28-12-2018 00:00 ||     d1    |   | 0.014 |
| 28-12-2018 00:15 ||     d1    |   | 0.013 |
| 28-12-2018 00:30 ||     d1    |   | 0.012 |
| 28-12-2018 00:45 ||     d1    |   | 0.011 |
|     :        :   ||     d1    |   |   :   |
| 28-12-2018 23:15 ||     d1    |   | 0.012 |
| 28-12-2018 23:30 ||     d1    |   | 0.017 |
| 28-12-2018 23:45 ||     d1    |   | 0.018 |
| 29-12-2018 00:00 ||     d2    |   | 0.019 |
| 29-12-2018 00:15 ||     d2    |   | 0.020 |
|      ....        ||     d2    |   |  ...  |
|        .         ||     .     |   |   .   |
|        .         ||     .     |   |   .   |
| 31-01-2019 23:45 ||     d2    |   |   .   |

Expected output:

|      date        || DeviceID  |   | Value |
| ---------------- || --------- |   | ----- |
| 28-12-2018 00:00 ||     d1    |   | 0.018 |
| 28-12-2018 00:15 ||     d1    |   | 0.017 |
| 28-12-2018 00:30 ||     d1    |   | 0.012 |
| 28-12-2018 00:45 ||     d1    |   | 0.010 |
|     :        :   ||     d1    |   |   :   |
| 28-12-2018 23:15 ||     d1    |   | 0.012 |
| 28-12-2018 23:30 ||     d1    |   | 0.013 |
| 28-12-2018 23:45 ||     d1    |   | 0.014 |
| 29-12-2018 00:00 ||     d2    |   | 0.019 |
| 29-12-2018 00:15 ||     d2    |   | 0.020 |
|      ....        ||     d2    |   |  ...  |
|        .         ||     .     |   |   .   |
|        .         ||     .     |   |   .   |
| 31-01-2019 23:45 ||     d2    |   |   .   |

I have tried with the following code but the main dataframe is not updating. The below code is reversing the values. Also, I have tried with inplace=True but getting an error.

df[df['DeviceID'].str.contains('d1') & df['date'].str.contains('28-12-2018')].Value.iloc[::-1]

I want to feed a different set of devices (e.g. d1, d3, d5, d9) and their corresponding dates (e.g. [28-12-2018, 30-12-2018] for d1, [03-01-2019, 05-01-2019, 09-01-2018] for d2 and so on). The reversed values for a given device and its corresponding dates should be reflected in the main dataframe.

1 Answers

One way I can think of is by reindexing, but in that case you need a list of all indices in the dataframe, so this should work:

# get the list of indices to reverse
indices_rev=df[df['DeviceID'].str.contains('d1') & df['date'].str.contains('28-12-2018')].iloc[::-1].index
        
# get list of indices to not reverse
indices_keep=df[~df['DeviceID'].str.contains('d1') | ~df['date'].str.contains('28-12-2018')].index
        
# add the lists
indices=indices_rev.append(indices_keep)
        
# reindex with the new list of indices
df=df.reindex(indices)
df
Related