简体   繁体   中英

creating a dummy variable combining other dummies in python

I want to combine three dummy variables into one. For example:

x1: 1 0 0 0 1

x2: 0 0 0 0 1

x3: 1 1 0 0 0

I want to create: x4: 1 1 0 0 1 (Takes 1 if any of the three dummies has 1, and takes 0 if all of them are zero)

Note: They are variables in a data frame. So the new variable will be a part of that data frame too.

I am new in python and I appreciate your help. Best

Let's say you define x as a grid:

x = [
    [1, 0, 0, 0, 1],
    [0, 0, 0, 0, 1],
    [1, 1, 0, 0, 0]
]

For each row, we can use any() to see if any of the items in the row is one. We can then turn the result (a boolean) into an integer with int() :

result = [int(any(row)) for row in x]

I'm not so sure what you mean by the new variable being part of the data frame.

I think the most literal way to create x4 is by using a bitwise OR operator in a list comprehension:

>>> x1=[1, 0, 0, 0, 1]
>>> x2=[0, 0, 0, 0, 1]
>>> x3=[1, 1, 0, 0, 0]
>>> x4=[x1[i]|x2[i]|x3[i] for i in range(len(x1))]
>>> x4
[1, 1, 0, 0, 1]

The list comprehension (see https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions ) builds a new list while iterating over the first, second, etc values of x1-x3. The bitwise OR operator (|) (see https://wiki.python.org/moin/BitwiseOperators ) each time evaluates to 1 if any of the 3 values is 1 and to 0 otherwise.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM