J. Jones J. Jones - 2 months ago 7
Python Question

How do I find an Index of a header in a csv file in Python?

My program list the headers of a CSV file to a user and asks him to pick an x and an y to plot. It works fine, but I don't want the user to type out the header string. I would rather find the index of each of the header and ask him to type a number instead. My csv file looks as follows:

time(s),speed(m/s),alt_a(m),....
25,62,10
45,70,20
30,50,30


Currently, the user has to type out for x, speed(m/s) I would rather the data shows up something like this and have the user just type 2.

1.time(s),2.speed(m/s),3.alt_a(m)


I looked a lot during the past two days and I can't seem to find any information of how would I even begin to do this.

import pandas as pd

df = pd.DataFrame.from_csv('data.csv',index_col=False)

while True:
print (list(df))
print ('Select X-Axis')
xaxis = input()
print ('Select Y-Axis')
yaxis = input()
break

df.plot(x= xaxis, y= yaxis1)

Answer

You can get the header with df.columns,

print(", ".join(["{0}.{1}".format(i,x) for i,x in enumerate(df.columns)]))
x_index = input("index of the x series:")
x_header = df.columns[x_index]
y_index = input("index of the y series:")
y_header = df.columns[y_index]
df.plot(x= x_header , y= y_header )

the first line creates a list of the headers in the format you specified 1.time(s),2.speed(m/s),3.alt_a(m) and prints it.

"{0}.{1}".format(i,x) creates a string in the format "i.x" where i is a counter and x is an element of the headers

The second line asks an input to the user, which would be the index 0,1,2.. in accordance to the previous list.

In the third line, df.columns[x_index] is the header that the user chose.