a = pd.DataFrame({
"one":[np.NAN,np.NAN,"e"],
"two":["a","s","d"],
"three":[1,2,2]
})
| 一 | 二 | 三 | |
|---|---|---|---|
| 0 | 楠 | 一個 | 1 |
| 1 | 楠 | s | 2 |
| 2 | e | d | 2 |
我想更改“一”列中滿足以下條件的值
- a["one"] 為空。
- a["三] 是 1。
所以我使用了布爾索引。
a[(a["one"].isnull()) & (a["three"]==1)]
| 一 | 二 | 三 | |
|---|---|---|---|
| 0 | 楠 | 一個 | 1 |
a[(a["one"].isnull()) & (a["three"]==1)].loc[a["one"]!=a["one"], "one"]
| 一 | |
|---|---|
| 0 | 楠 |
a[(a["one"].isnull()) & (a["three"]==1)].loc[a["one"]!=a["one"], "one"] = "replaced"
但是資料框“a”仍然是“a”。Nan 值不會被替換為“替換”。沒有改變。
我想知道為什么。
uj5u.com熱心網友回復:
但是資料框“a”仍然是“a”。Nan 值不會被替換為“替換”。沒有改變。我想知道為什么。
如果檢查evaluation order matters說明您分配給視圖a[(a["one"].isnull()) & (a["three"]==1)]而不是原始資料幀。
正確的方法是使用DataFrame.loc布爾掩碼和列名設定:
a.loc[a["one"].isna() & (a["three"]==1), "one"] = "replaced"
print (a)
one two three
0 replaced a 1
1 NaN s 2
2 e d 2
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/505721.html
上一篇:從串列中洗掉重復的子字串
