Home > Mobile >  Using a classifier column to filter dataframe in pandas
Using a classifier column to filter dataframe in pandas

Time:10-14

I think this should be asked before, but with the keywords I couldn't find an answer to this simple question.

I have a dataframe df, and a classifier output clf. I would like the output to be the nth element of the row, as specified by the nth element the classifier, for all rows of the dataframe. so the output is basically [df.iloc[0,1], df.iloc[1,0], df.iloc[2,2], where [1,0,2] is clf, the classifier

import pandas as pd

data = {'zero':[1,2,3], 'one':[4,5,6], 'two':[7,8,9]}
df = pd.DataFrame(data)
clf = [1,0,2]
output = [4,2,9]

Thanks for any help. Much appreciated

CodePudding user response:

Numpy solution with indexing by range and clf is:

output = df.to_numpy()[range(len(df)), clf].tolist()
print (output)
[4, 2, 9]

CodePudding user response:

try :

print([df.iloc[i, j] for i, j in enumerate(clf)])

[4, 2, 9]
  • Related