添加column3:
df['column3'] = np.where((df['column2']) == 1, '1', 0)
現有表的 2 列不輸入 1,結果為column30
column1 column2 column3
0 1 0
1 0 0
0 0 0
0 1 0
1 0 0
uj5u.com熱心網友回復:
FTR,問題似乎是該列具有字串值,這意味著沒有值將等于1. 改用"1":
df['column3'] = np.where(df['column2'] == "1", "1", 0)
uj5u.com熱心網友回復:
所以下面的代碼對我有用。它與您的代碼基本相同。
import pandas as pd
import numpy as np
d = {'column1': [0, 1, 0, 0, 1], 'column2': [1, 0, 0, 1, 1], 'column3': [0, 0, 0, 0, 0]}
df = pd.DataFrame(data=d)
df['column3'] = np.where((df['column2']) == 1 , '1', 0)
```
The output is:
[enter image description here][1]
[1]: https://i.stack.imgur.com/sgodK.png
So please check the datatype of "column2", if it is a string the condition may be false.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/433856.html
