mk2080
mk2080

Reputation: 922

Create new column if all values in a column list are zero

I want to create a new column which looks at a list of columns (colList) and returns zero if every value in those columns is zero and 1 for all else.

colList = ['Value1', 'Value2', 'Value3']

Value1 Value2 Value3 Value4
    0        0        0      1
    10       8        1      3
    1        0        0      5
Value1 Value2 Value3 Value4 newcol
0        0        0      1     0
10       8        1      3     1
1        0        0      5     1

Upvotes: 2

Views: 730

Answers (1)

Chris
Chris

Reputation: 29742

Use pandas.DataFrame.any with axis==1:

df["newcol"] = df[colList].any(1).astype(int)
print(df)

Output:

   Value1  Value2  Value3  Value4  newcol
0       0       0       0       1       0
1      10       8       1       3       1
2       1       0       0       5       1

Upvotes: 1

Related Questions