Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return headers of columns that match a criteria for every row in a pandas dataframe?

I have a pandas dataframe df of the form :

     Col1      Col2      Col3      Col4

0    True      False     True      False
1    False     False     False     False
2    False     True      False     False
3    True      True      True      True

Here True and False are boolean values.

I am trying to generate a new pandas dataframe new_df which should look like:

     Matched_Cols

0    [Col1, Col3]
1    []
2    [Col2]
3    [Col1, Col2, Col3, Col4]

What is the most efficient way to achieve this?

like image 592
Melsauce Avatar asked Dec 10 '25 18:12

Melsauce


2 Answers

Approach #1

Here's with array-data processing -

def iter_accum(df):
    c = df.columns.values.astype(str)
    return pd.DataFrame({'Matched_Cols':[c[i] for i in df.values]})

Sample output -

In [41]: df
Out[41]: 
    Col1   Col2   Col3   Col4
0   True  False   True  False
1  False  False  False  False
2  False   True  False  False
3   True   True   True   True

In [42]: iter_accum(df)
Out[42]: 
               Matched_Cols
0              [Col1, Col3]
1                        []
2                    [Col2]
3  [Col1, Col2, Col3, Col4]

Approach #2

Another with slicing on array-data and some boolean-indexing -

def slice_accum(df):
    c = df.columns.values.astype(str)
    a = df.values
    vals = np.broadcast_to(c,a.shape)[a]
    I = np.r_[0,a.sum(1).cumsum()]
    ac = []
    for (i,j) in zip(I[:-1],I[1:]):
        ac.append(vals[i:j])
    return pd.DataFrame({'Matched_Cols':ac})

Benchmarking

Other proposed solution(s) -

# @jezrael's soln-1
def jez1(df):
    return df.apply(lambda x: x.index[x].tolist(), axis=1)

# @jezrael's soln-2
def jez2(df):
    return df.dot(df.columns + ',').str.rstrip(',').str.split(',')

# @Shubham Sharma's soln
def Shubham1(df):
    return df.agg(lambda s: s.index[s].values, axis=1) 

# @sammywemmy's soln
def sammywemmy1(df):
    return pd.DataFrame({'Matched_Cols':[np.compress(x,y) for x,y in zip(df.to_numpy(),np.tile(df.columns,(len(df),1)))]})

Using benchit package (few benchmarking tools packaged together; disclaimer: I am its author) to benchmark proposed solutions.

import benchit
funcs = [iter_accum,slice_accum,jez1,jez2,Shubham1,sammywemmy1]
in_ = {n:pd.DataFrame(np.random.rand(n,n)>0.5, columns=['Col'+str(i) for i in range(1,n+1)]) for n in [4,20,100,200,500,1000]}
t = benchit.timings(funcs, in_, input_name='Len')
t.rank()
t.plot(logx=True)

enter image description here

like image 146
Divakar Avatar answered Dec 13 '25 08:12

Divakar


You can filter for each row index values, what are columns names in original DataFrame and then convert to lists:

df['Matched_Cols'] = df.apply(lambda x: x.index[x].tolist(), axis=1)

Or use DataFrame.dot for matrix multiplication with columns names with separator, removed last separator value by Series.str.rstrip and last use Series.str.split:

df['Matched_Cols'] = df.dot(df.columns + ',').str.rstrip(',').str.split(',')

print (df)
    Col1   Col2   Col3   Col4              Matched_Cols
0   True  False   True  False              [Col1, Col3]
1  False  False  False  False                        []
2  False   True  False  False                    [Col2]
3   True   True   True   True  [Col1, Col2, Col3, Col4]
like image 42
jezrael Avatar answered Dec 13 '25 06:12

jezrael