Python help - How to display a numbered list of all the column header names?

May i know how can i display a numbered list of all the column header names which i have already import the header names from csv using Python’s open() and readline().

I got my header using:

f= open("data.csv", "r", encoding='utf8')   
header = f.readline()
print(header)

The output was:

Name,Index,Age,Year,Jobcat,Dept

But i would like to display a numbered list of all the column header names, for eg. I would like my output to be:

0 Name
1 Index
2 Age
3 Year
4 Jobcar
5 Dept

Thank you very much in advance.

You’d get that output in a single string so you’d want to split that string into multiple parts based on that specific delimiter. Then you could iterate through the split string in a loop or similar. To get the numbering something like enumerate would be really useful.

You might have an easier time if you use the built-in csv library- csv — CSV File Reading and Writing — Python 3.9.5 documentation for working with csv files.

If you don’t use that library then at least consider opening your files using the with statement as it greatly lowers the risk of unexpected behaviour- https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

2 Likes

Hi @tgrtim,

Thank you very much.

The solution was very helpful & easy to understand.

Thank you for your explanation.

1 Like

Hi @tgrtim

Sorry following the on top question, after which, I would like to get user to choose 2 columns, so as to get the correlation but I can’t seem to get it with my code below:

first_column = input("Enter the number for the first column: ")
second_column = input("Enter the number for the second column: ")

x = int(first_column)
y = int(second_column)

column1 = np_orders[x]
column2 = np_orders[y]
np.corrcoef(column1, column2)

If it’s a different question please use a different thread in the future (this is so titles match questions and the thread can be of use for other users).

You might want to explain what happens (or does not happen) and what np_orders actually is. Is there an error? Is there an unexpected output?

1 Like

Hi @tgrtim

Okay thank you, i will create another thread.

Sorry about it.

1 Like