简体   繁体   中英

How to create multiple column list of booleans from given list of integers in phython?

I am new to Python. I want to do following.

Input: A list of integers of size n . Each integer is in a range of 0 to 3.

Output: A multi-column (4 column in this case as integer range in 0-3 = 4) numpy list of size n . Each row of the new list will have the column corresponding to the integer value of Input list as True and rest of the columns as False.

Eg Input list : [0, 3, 2, 1, 1, 2], size = 6, Each integer is in range of 0-3

Output list :

Row 0: True  False  False  False
Row 1: False False  False  True
Row 2: False False  True   False
Row 3: False True   False  False
Row 4: False True   False  False
Row 5: False False  True   False

Now, I can start with 4 columns. Traverse through the input list and create this as follows,

output_columns[].
for i in Input list:
    output_column[i] = True
Create an output numpy list with output columns

Is this the best way to do this in Python? Especially for creating numpy list as an output.

If yes, How do I merge output_columns[] at the end to create numpy multidimensional list with each dimension as a column of output_columns.

If not, what would be the best (most time efficient way) to do this in Python?

Thank you,

Is this the best way to do this in Python?

No, a more Pythonic and probably the best way is to use a simple broadcasting comparison as following:

In [196]: a = np.array([0, 3, 2, 1, 1, 2])

In [197]: r = list(range(0, 4))

In [198]: a[:,None] == r
Out[198]: 
array([[ True, False, False, False],
       [False, False, False,  True],
       [False, False,  True, False],
       [False,  True, False, False],
       [False,  True, False, False],
       [False, False,  True, False]])

You are creating so called one-hot vector (each row in matrix is a one-hot vector meaning that only one value is True).

mylist = [0, 3, 2, 1, 1, 2]
one_hot = np.zeros((len(mylist), 4), dtype=np.bool)
for i, v in enumerate(mylist):
    one_hot[i, v] = True

Output

array([[ True, False, False, False],
       [False, False, False,  True],
       [False, False,  True, False],
       [False,  True, False, False],
       [False,  True, False, False],
       [False, False,  True, False]], dtype=bool)

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