1

I have a csv file or pd dataframe object with labels on both axis (columns and rows). I need to check the values of each cell and if the value is True, I need to print the corresponding axis labels (both axis) for the values. I spent some time and couldn't find a solution out there in Python. Really appreciate any help.

Something like this:

['', 'column_name_1', 'column_name_2', 'column_name_3',...] 
['Row_1_name', 'False', 'False', 'True'...] 
['Row_2_name', 'False', 'False', 'True'...]

Thanks for any assistance.

2
  • Could you give a little more detail about the dataframe? And do you need to save the labels in some way or just list them? Commented Jan 23, 2022 at 22:03
  • 1
    please see my edits, this is the csv format. Commented Jan 23, 2022 at 23:14

1 Answer 1

1

Here is a simple example that prints index and column of all True values in a dataframe by applying a print function to all columns:

import pandas
import io

data = '''col1,col2
label1,False,True
label2,True,False
label3,False,True'''

df = pd.read_csv(io.StringIO(data), engine='python')

def print_labels(x):
    for label, val in x.iteritems():
        if val: #insert your own validation here (or filter the column before the loop)
            print(label, x.name)

df.apply(print_labels, axis=0)

Output:

label2 col1
label1 col2
label3 col2
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much, I will try this. Have a good one!
Why did label2 print before label1?
@ZachYoung because axis=0 passes columns. Use axis=1 for a row-wise approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.