【问题标题】:Replace row values by condition if they are in certain time range如果它们在特定时间范围内,则按条件替换行值
【发布时间】:2021-06-26 18:08:06
【问题描述】:

我试图用两个条件替换 DataFrame 行中的某些值。首先,它们必须在一定的时间范围内。此外,此时间范围内的值必须在要替换的值列表中。

我的最佳尝试:

df = df[df.between_time('06:00', '20:00')].replace([0, 1, 2, 3], np.nan, inplace=True)

这是我得到的错误:

ValueError: Boolean array expected for the condition, not object

DataFrame 如下所示:

datetime vehicles
2021-01-01 00:00:00 13.0
2021-01-01 00:15:00 9.0

等等……

主要目标是用 NaN 替换 06:00 到 20:00(晚上 8 点)之间的所有值(如果它们

【问题讨论】:

    标签: python pandas dataframe replace time-series


    【解决方案1】:
    import pandas as pd
    

    首先将您的“日期时间”列转换为日期时间dtype(如果它已经是日期时间[ns],则忽略此步骤):

    df['datetime']=pd.to_datetime(df['datetime'])
    

    然后将您的“日期时间”列作为索引(如果它已经作为索引,则忽略此步骤):

    df=df.set_index('datetime')
    

    现在使用between_time() 方法和apply() 方法:

    resultdf=df.between_time('00:06:00', '00:20:00')['vehicles'].apply(lambda x:np.nan if x<=3 else x)
    

    最后:

    resultdf.values.shape=(2,1)
    df.loc[resultdf.index]=resultdf
    

    现在,如果您打印 df,您将获得所需的输出

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-07
      • 2020-12-30
      • 2021-12-13
      • 1970-01-01
      • 2015-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多