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.
-
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?KevOMalley743– KevOMalley7432022年01月23日 22:03:09 +00:00Commented Jan 23, 2022 at 22:03
-
1please see my edits, this is the csv format.Matthew– Matthew2022年01月23日 23:14:16 +00:00Commented Jan 23, 2022 at 23:14
1 Answer 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
answered Jan 23, 2022 at 22:14
RJ Adriaansen
9,7192 gold badges16 silver badges29 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Matthew
Thank you so much, I will try this. Have a good one!
Zach Young
Why did label2 print before label1?
RJ Adriaansen
@ZachYoung because
axis=0 passes columns. Use axis=1 for a row-wise approach.lang-py