![](/img/trans.png)
[英]Is there any way to replace values with different values in the same row if they meet a certain condition using a for loop?
[英]Replace row values by condition if they are in certain time range
我试图用两个条件替换 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 看起来像这样:
约会时间 | 车辆 |
---|---|
2021-01-01 00:00:00 | 13.0 |
2021-01-01 00:15:00 | 9.0 |
等等...
主要目标是用 NaN 替换 06:00 到 20:00(晚上 8 点)之间的所有值,如果它们 <= 3。
import pandas as pd
首先将您的 'datetime' 列转换为 datetime dtype(如果它已经是 datetime[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
你会得到你想要的 output
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.