How do I find an Index of a header in a csv file?
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)
Posted Oct 3, 2016, 3:33 PM UTC
There's lots of ways. For instance, you could use an
OrderedDictandenumerate:Thanks I will try this and will report back.
Thank you so much that worked! Could you elaborate on the code a bit with comments so I can learn what it exactly is doing so I am not just copy/pasting.
Thank you!
enumerate()can take any argument thatlist()can (an "iterable") and it assigns a sequential number to each element. So it can accept a dataframe and returns a list of tuples:It also takes an optional argument to set the start number:
A list of 2-tuples like that is one of the types of objects that the dictionary constructor can use. So we can quickly turn that into a dictionary:
Which is good because in order to turn the user input into text this is exactly what we need.
A problem is that dictionaries are not guaranteed to maintain the order of the elements (although for small numeric keys they often will), so we use an OrderedDict instead to ensure the options are printed in order.
Did that answer your question? If not tell me what exactly you are confused about.
Yes, it did, thank you so much I have been bashing my head against the wall trying to come up with something similar to this.
One question, if I do want more than 1 y-axis could I do this: df.plot(x= headings[xaxis], y= heading[yaxis], y1= heading[yaxis]? also would that scale the different yaxis? or is that a whole different thing? EDIT: I took an attempt at it. However, I couldn't get it work.
Sorry, I don't know much about pandas. Your code looks ok, but I don't have time to test it and see whats wrong. Hopefully someone else will jump in.