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

19
novel_yet_trivial•

There's lots of ways. For instance, you could use an OrderedDict and enumerate:

from collections import OrderedDict
headings = OrderedDict(enumerate(df,1))
for num, heading in headings.items():
    print("{}) {}".format(num, heading))

print ('Select X-Axis')
xaxis = int(input())

print ('Select Y-Axis')
yaxis = int(input())

df.plot(x= headings[xaxis], y= headings[yaxis])
2
IsitwhenipeeOP•

Thanks I will try this and will report back.

1
IsitwhenipeeOP•

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!

1
novel_yet_trivial•

enumerate() can take any argument that list() can (an "iterable") and it assigns a sequential number to each element. So it can accept a dataframe and returns a list of tuples:

>>> list(enumerate(df))
[(0, 'time(s)'), (1, 'speed(m/s)'), (2, 'alt_a(m)')]

It also takes an optional argument to set the start number:

>>> list(enumerate(df, 1))
[(1, 'time(s)'), (2, 'speed(m/s)'), (3, 'alt_a(m)')]

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:

>>> dict(enumerate(df, 1))
{1: 'time(s)', 2: 'speed(m/s)', 3: 'alt_a(m)'}

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.

2
IsitwhenipeeOP•

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.

import pandas as pd
import matplotlib.pyplot as plt

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


from collections import OrderedDict
headings = OrderedDict(enumerate(df,1))
for num, heading in headings.items():
    print("{}) {}".format(num, heading))

print ('Select X-Axis')
xaxis = int(input())

print ('Select Y-Axis')
yaxis = int(input())

print ('Select Z-Axis')
zaxis = int(input())


fig, ax1 = plt.subplots(1,1)

df.headings[yaxis].plot(ax=ax1, color='blue')
ax2 = ax1.twinx()
df.headings[zaxis].plot(ax=ax2, color='green')

plt.show()
1
novel_yet_trivial•

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.

2
chrisutpg•

I'm having a bit trouble understanding exactly what you want the user to do?

2
IsitwhenipeeOP•

The user selects the x axis and y axis from a list that is printed from a csv file. I want the user to be able to just type out a number to select something from the list and not have to type out the entire string. For example:

when my program asks for x axis: right now he has to type Time(s) I want to assign Time(s) to a value for example 1. So that he will just type 1.

1