DBS DBS - 2 months ago 10
Python Question

Retrieve header of column if it has a certain value

I have a csv file with headers in the following format:

column1
,
column2
,
column3


True
,
False
,
False


False
,
True
,
True


In python, I would like to print the column name if a value of
True
is under it (
column1
and then for the next row
column2
and
column3
). In the code I have below, it's printing every column.

with open(reportOut, 'r') as f:
reader = csv.reader(f, skipinitialspace=True)
header = next(reader)
for row in reader:
if 'True' in row:
print(header)

Answer

This works:

import csv

with open("my.csv", 'r') as f:
    reader = csv.reader(f, skipinitialspace=True)
    headers = next(reader)
    # Start counting from 2 (Row #1 is headers)
    for row_number, row in enumerate(reader, 2):
        for column, val in enumerate(row):  # On each column in the row
            if val == "True":  # Check for the value
                # Print the header according to the column number
                print(row_number, headers[column])

Output:

2 column1
3 column2
3 column3
Comments