![](/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.