我有一個如下的df
Date Flow
0 1981-01-01 103.432860
1 1981-01-02 102.982800
2 1981-01-03 102.121150
3 1981-01-04 100.92662
... ....
xx 2020-12-31 150.123
我需要將 1 月 1 日的流量值替換為 0.00
df['month'] = df['Date'].dt.month_name()
df['dom']= df['Date'].dt.day
for ind in df.index:
df.loc[(df['month'] == 'January') & (df['dom'] == '01'), 'Flow'] = 0
df.head()
Results:
Date Flow month dom
0 1981-01-01 103.432860 January 1
1 1981-01-02 102.982800 January 2
2 1981-01-03 102.121150 January 3
3 1981-01-04 100.926620 January 4
它不作業
uj5u.com熱心網友回復:
使用 int 而不是字串
正如 MattDMo 指出的那樣,您編碼失敗的原因是因為您正在過濾df["dom"] == "01"而不是df["dom"] == 0. 因為 dom 以整數而不是字串表示,所以它無法匹配任何列。
一條建議
與其回圈遍歷資料幀的每一行,不如使用 loc 僅選擇要更改的行。
df.loc[(df["month"] == "January") & (df["dom"] == 1), "Flow"] = 0
請注意,您需要將每個過濾器括在括號中以允許列邏輯,就像您所做的那樣。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/531765.html
上一篇:使用R修改檔案名中時間戳的時區
