我想根據日期時間索引向資料框添加一個新列。
我使用了以下代碼:我已經將日期值設定為索引,以便我使用時間索引。
new_col= []
start_date= pd.to_datetime('2020-03-01 00:00:00')
end_date= pd.to_datetime('2020-03-07 00:00:00')
for idx in range(len(df)):
if df.index[idx] => start_date and df.index[idx] <= end_date:
new_col.append(1)
else:
new_col.append(2)
df["newC"] = new_col
我仍然收到一個錯誤,即 df 和新列的長度不相等 - 表明新列的長度更大。我嘗試了 numpy where 方法,但效果不佳。
有沒有更好的方法可以根據特定時間段在新列中添加值,例如在這種情況下,從 '2020-03-01 00:00:00' 到 '2020-03-07 00:00:00' ?
uj5u.com熱心網友回復:
這應該有效:
df["newC"] = pd.Series(df.index, index=df.index).apply(lambda dt: 1 if start_date <= dt <= end_date else 2)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/516242.html
下一篇:如何將字串轉換為日期時間格式?
