'Adding a new column in dataframe conditionally
I have a dataframe as follows:
| Time | A | B |C |
| ---- |-- | ---- |---- |
| 1.0 | 0 | 1 | 0 |
| 2.0 | 1 | 1 | 0 |
| 3.0 | 1 | 1 | 1 |
| 4.0 | 0 | 1 | 1 |
| . | . | . | . |
| 1000.0| 1 | 1 | 1 |
I want to write to a new column D=1 whenever A==1 & B==1 & C==1 and 0 otherwise
Solution 1:[1]
This is a possible solution, although it might not be the more efficient:
df["D"] = ((df["A"] == 1) & (df["B"] == 1) & (df["C"] == 1)).astype(int)
This one looks better, and should return the same output as the previous one:
df["D"] = (df["A"] & df["B"] & df["C"]).astype(int)
Another option to check if each column is equal to one and then sum their values (credit to @enke for removing the binary constrain of the old version):
df["D"] = (df[["A", "B", "C"]].eq(1).sum(axis=1) == 3).astype(int)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
