gpt4 book ai didi

Python Pandas 条件无法准确识别行

转载 作者:太空宇宙 更新时间:2023-11-03 14:01:13 24 4
gpt4 key购买 nike

这是 Jupyter Notebook 的输入和输出。我需要帮助来确定无法准确选择和设置“went_out”列中的数据的原因。

enter image description here

两个红色下划线单元格都应该显示其所在行的日期时间列中的数据,但只有一个单元格准确地显示了它。事实证明,许多符合我的条件的行没有被选择和设置。

enter image description here

这是我使用的代码示例:

# your answer here
df.loc[(df['reading_type'] == 'motion') & (df['value'] == 255), 'event'] = 'motion on'
df.loc[(df['reading_type'] == 'motion') & (df['value'] == 0), 'event'] = 'motion off'

df2 = df.loc[(df['reading_type'] == 'door') | (df['event'] == 'motion on')].copy()
df2.loc[(df['event'] == 'door close') & (df['event'].shift(-1) == 'door open'), 'went_out'] = df2['datetime']
df2

以下是 jupyter 笔记本文件和 csv 文件的链接:

  1. Jupyter 笔记本: https://drive.google.com/file/d/15f6NQrM4UoAZlzRhK35TOKyhPJnmWWdU/view?usp=sharing

  2. CSV 文件: https://drive.google.com/file/d/1hZudSVbT91ESj2qkzrJ--CbVdrzVCmce/view?usp=sharing

最佳答案

据我了解,您正在尝试写下门关闭时的日期和时间。这可能是您想要的解决方案的一部分。您可以仅使用门关闭条件来索引“went_out”列,而不是查找门打开然后关闭的条件。

df.loc[(df['reading_type'] == 'door') & (df['value'] == 255), 'event'] = 'door on'
df.loc[(df['reading_type'] == 'door') & (df['value'] == 0), 'event'] = 'door off'

df2 = df[df['reading_type'] == 'door'].copy()
# The line below is modified
df2.loc[df2['event'] == 'door off', 'went_out'] = df2[df2['event'] == 'door off']['datetime']
print(df2)

输出如下:

    id  datetime    device  location    reading_type    value   event   went_out
284 284 2018-01-01 07:57:56 Door door door 255.0 door on NaN
285 285 2018-01-01 07:58:12 Door door door 0.0 door off 2018-01-01 07:58:12
294 294 2018-01-01 08:29:25 Door door door 255.0 door on NaN
295 295 2018-01-01 08:29:38 Door door door 0.0 door off 2018-01-01 08:29:38
357 357 2018-01-01 09:16:38 Door door door 255.0 door on NaN
361 361 2018-01-01 09:17:40 Door door door 0.0 door off 2018-01-01 09:17:40

希望这对您有所帮助。

编辑
开门后关门时获取日期和时间的条件

df2.loc[((df2['event'].shift(-1) == 'door on') & (df2['event']=='door off') ), 'went_out'] = df2[df2['event']=='door off']['datetime']

print(df2[df2['event'] == 'door off'])

id datetime device location reading_type value event went_out
285 285 2018-01-01 07:58:12 Door door door 0.0 door off 2018-01-01 07:58:12
295 295 2018-01-01 08:29:38 Door door door 0.0 door off NaN
361 361 2018-01-01 09:17:40 Door door door 0.0 door off 2018-01-01 09:17:40
509 509 2018-01-01 15:50:46 Door door door 0.0 door off 2018-01-01 15:50:46

请告诉我这是否可以解决您的问题。

关于Python Pandas 条件无法准确识别行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49228252/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com