我有一個這樣的資料框
test = pd.DataFrame({'col1':[10,20,30,40], 'col2':[5,10,15,20], 'col3':[6,12,18,24]})
test
資料框看起來像
col1 col2 col3
0 10 5 6
1 20 10 12
2 30 15 18
3 40 20 24
我想用零替換 col2 或 col3 中大于 10 的值。我想為此使用 loc 函式。
我想要的輸出是:
col1 col2 col3
0 10 5 6
1 20 10 0
2 30 0 0
3 40 0 0
我試過以下解決方案
cols_to_update = ['col2', 'col3']
test.loc[test[cols_to_update]>10]=0
test
它顯示以下錯誤:
KeyError: "None of [Index([('c', 'o', 'l', '1'), ('c', 'o', 'l', '2')], dtype='object')] are in the [index]"
當我使用單列測驗條件時,它不顯示“KeyError”,但現在它也替換了其他兩列中的值
test.loc[test['col2']>10]=0
test
輸出是
col1 col2 col3
0 10 5 6
1 0 0 0
2 0 0 0
3 0 0 0
請指導
- 我們可以為此目的使用 loc 嗎
- 為什么 loc 會這樣
- 什么是有效的解決方案我已經經歷過類似的問題但沒有找到確切的解釋。我是 ML 學生,并且不熟悉這種板塊形式,如果問題的措辭或格式不正確,請原諒我。謝謝
uj5u.com熱心網友回復:
我會numpy.where用來有條件地替換多列的值:
import numpy as np
cols_to_update = ['col2', 'col3']
test[cols_to_update] = np.where(test[cols_to_update] > 10, 0, test[cols_to_update])
該運算式test[cols_to_update] > 10為您提供了一個布爾掩碼:
col2 col3
0 False False
1 False True
2 True True
3 True True
然后,np.where采值0每當這個掩碼是True或它選擇相應的原始資料test[cols_to_update],每當該掩模是False。
您的解決方案test.loc[test[cols_to_update]>10]=0不起作用,因為在這種情況下 loc 需要布爾一維系列,而test[cols_to_update]>10仍然是具有兩列的資料幀。這也是您不能使用 loc 解決此問題的原因(至少在不回圈列的情況下不能):第 2 列和第 3 列的值滿足條件的索引> 10不同。
當將loc在這種情況下,合適嗎?例如,如果您想在第 2 列和第 3 列中的任何一個大于 10 時將這兩個列都設定為零:
test.loc[(test[cols_to_update] > 10).any(axis=1), cols_to_update] = 0
test
# out:
col1 col2 col3
0 10 5 6
1 20 0 0
2 30 0 0
3 40 0 0
在這種情況下,您使用 1D 系列 ( (test[cols_to_update] > 10).any(axis=1)) 進行索引,這是loc.
uj5u.com熱心網友回復:
您可以使用where:
import pandas as pd
test = pd.DataFrame({'col1':[10,20,30,40], 'col2':[5,10,15,20], 'col3':[6,12,18,24]})
test[['col2', 'col3']] = test[['col2', 'col3']].where(test[['col2', 'col3']] <= 10, 0)
輸出:
| 第 1 列 | 列2 | 第 3 列 | |
|---|---|---|---|
| 0 | 10 | 5 | 6 |
| 1 | 20 | 10 | 0 |
| 2 | 30 | 0 | 0 |
| 3 | 40 | 0 | 0 |
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/362562.html
上一篇:用檔案標記分析情緒
