python - 如何根据pandas数据框中的多个条件反转列值?

标签 python pandas dataframe

我想根据多个条件反转特定列的值。我有一个包含(日期、DeviceID、值)列的时间序列数据集。

输入数据:

|      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    |   |   .   |

预期输出:

|      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    |   |   .   |

我已尝试使用以下代码,但主数据框未更新。下面的代码正在反转这些值。另外,我尝试过 inplace=True 但出现错误。

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

我想提供一组不同的设备(例如 d1、d3、d5、d9)及其相应的日期(例如 d1 为 [28-12-2018, 30-12-2018],[03-01-2019] 、05-01-2019、09-01-2018] 对于 d2 等等)。给定设备的反转值及其相应日期应反射(reflect)在主数据框中。

最佳答案

我能想到的一种方法是重新索引,但在这种情况下,您需要数据框中所有索引的列表,所以这应该可行:

# 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

关于python - 如何根据pandas数据框中的多个条件反转列值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67384545/

相关文章:

python - 创建大型 Pandas DataFrames : preallocation vs append vs concat

python - Pandas :返回值的第一个实例和最后一个实例的索引值

python - 如何连接多索引列数据框

python - 使用 Python 将 2 个独立的 .csv 文件放在一张图表上

python - 将每个项目与一行中的最后一个非空值配对

python - 基于分类列创建填充随机元素的新列

python - 发现打开文件错误 : TypeError: coercing to Unicode: need string or buffer, 列表

python - 不要提交超过 11 点的时间 :59 pm

python - python代码中的相对路径 - 最佳实践

Python 不一致的日期时间解析