Doc Doc - 21 days ago 6x
Python Question

Extract header names from a CSV and use it to plot against each other in Python?

I am pretty new to python and coding in general. I have this code so far.

import numpy as np
import matplotlib.pyplot as plt

data = np.loadtxt('data.csv', delimiter=',', skiprows=1)

mSec = data[:,0]
Airspeed = data[:,10]
AS_Cmd = data[:,25]
airspeed = data[:,3]

plt.rc('xtick', labelsize=25) #increase xaxis tick size
plt.rc('ytick', labelsize=25) #increase yaxis tick size

fig, ax = plt.subplots(figsize=(40,40), edgecolor='b')

ax.plot(mSec, Airspeed, label='Ground speed [m/s]')
ax.plot(mSec, AS_Cmd, label='Voltage [V]')

fig.savefig('trans2.png', dpi=(200), bbox_inches='tight') #borderless on save

However, I don't want to individually read every data column there is. I want to be able to load a csv file and have it read out all column names, then asks the users what you want for your x-axis and y-axis and plots that graph. The csv file format is:


Here is my attempt at the code but I am missing a lot of information:

import numpy as np
import matplotlib.pyplot as plt

data = np.loadtxt('data.csv', delimiter=',')
## names = where I will store the column names

white True:
## display names to user
print ('Pick your x-axis')
xaxis = input()
print ('Pick your y-axis')
yaxis1 = input()
print('pick a 2nd y-axis or enter none')
yaxis2 = input()
if input()= 'none'
else continue
#plot xaxis vs yaxis vs 2nd yaxis

I understand the loop is not correct. I don't want anyone to correct me on that I will figure it out myself, however, I would like a way to access those values from the CSV file so that I can use it in that method.


Using pandas you can do:

import pandas as pd
data = pd.read_csv("yourFile.csv", delimiter=",")

and plot columns with names ColName1, ColName2 against each other with:

data.plot(x='Col1', y='Col2')

If you have a first line in the csv file with the desired names of the columns, pandas will pick those automatically, otherwise you can play with the header argument of read_csv.