1

Predict returns me a numpy array (which consists only from 0 and 1) for every column.

How to print names of columns which have 1 and dont show columns which have 0?

predict

[[0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], 
 [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0.], 
 [0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]]

I have list of columns names - columns_names:

['1', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '2', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '3', '30', '31', '32', '33', '34', '4', '5', '6', '7', '8', '9']

type(predict) - numpy.ndarray

type(columns_names) - list
lemon
  • 737
  • 6
  • 17

2 Answers2

2

You can use pandas dataframes to help with labelling your numpy matrix.

import pandas as pd

predict = [[0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], 
 [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0.], 
 [0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]]

columns_names = ['1', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '2', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '3', '30', '31', '32', '33', '34', '4', '5', '6', '7', '8', '9']

df = pd.DataFrame(predict, columns=columns_names)
df.columns[df.any()].tolist()

Output:

['15', '17', '24', '6']

You can use,

df.apply(lambda x: df.columns[x.eq(1)].tolist(), axis=1).tolist()

Output:

[['17', '24'], ['6'], ['15', '24']]
Scott Boston
  • 147,308
  • 15
  • 139
  • 187
1

You can do this with a simple list comprehension without the need to import any external modules.

list(i for i,j in zip(columns_names, predict) if j)

This is a concept known as "masking." You can read more about it at this post: Python: Elegant and efficient ways to mask a list

AmphotericLewisAcid
  • 1,824
  • 9
  • 26