![](/img/trans.png)
[英]Creat a new column which depends on the range of values of other columns in pandas
[英]A new column in pandas that depends on values of the other rows
我有一個示例數據:
column1 column2 column3 column4
0. 1. 1. 0
1. 1. 1. 1
0. 0. 0. 0
1. 1. 1. 0
1. 1. 1. 1
我想創建一個新列(輸出),如果 dataframe 的至少一個行值為 1,則顯示 1,如果行全為 0,則顯示 0。
output 應如下所示:
column1 column2 column3 column4. output
0. 1. 1. 0. 1
1. 1. 1. 1. 1
0. 0. 0. 0. 0
1. 1. 1. 0. 1
1. 1. 1. 1. 1
使用DataFrame.any
測試是否匹配至少一個匹配:
df['output'] = df.eq(1).any(axis=1).astype(int)
#alternative
df['output'] = np.where(df.eq(1).any(axis=1), 1, 0)
#if only 0,1 values is possible use
#df['output'] = df.any(axis=1).astype(int)
利用:
df['output'] = np.any(df.eq(1)., axis = 1).astype(int)
您可以檢查該行中所有列的總和是否優於0
df.output = df.apply(lambda row: int(row.sum() > 0), axis=1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.