![](/img/trans.png)
[英]Create multiple columns based on values in single column in Pandas DataFrame
[英]Create a Single column using values fom multiple columns
我試圖根據來自三列的值在Pandas數據框中創建一個新列,如果每列的值['A','B','C']大於5,則輸出= 1,輸出=如果列['A','B','C']中的任何一個值小於0,則返回0。5數據幀如下所示:
A B C
5 8 6
9 2 1
6 0 0
2 2 6
0 1 2
5 8 10
5 5 1
9 5 6
預期產量:
A B C new_column
5 8 6 1
9 2 1 0
6 0 0 0
2 2 6 0
0 1 2 0
5 8 10 1
5 5 1 0
9 5 6 1
我嘗試使用此代碼,但未提供所需的輸出:
conditions = [(df['A'] >= 5) , (df['B'] >= 5) , (df['C'] >= 5)]
choices = [1,1,1]
df['new_colum'] = np.select(conditions, choices, default=0)
您需要按&
進行bitwise AND
鏈條件:
conditions = (df['A'] >= 5) & (df['B'] >= 5) & (df['C'] >= 5)
或使用DataFrame.all
檢查行中的所有值是否均為True
:
conditions = (df[['A','B','C']] >= 5 ).all(axis=1)
#if need all columns >=5
conditions = (df >= 5 ).all(axis=1)
然后將mask轉換為True, False
到1, 0
整數:
df['new_colum'] = conditions.astype(int)
或使用numpy.where
:
df['new_colum'] = np.where(conditions, 1, 0)
print (df)
A B C new_colum
0 5 8 6 1
1 9 2 1 0
2 6 0 0 0
3 2 2 6 0
4 0 1 2 0
5 5 8 10 1
6 5 5 1 0
7 9 5 6 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.