简体   繁体   中英

How to plot two specific columns from a csv file in python

I am new to python and may be missing some details when attempting to plot. I am trying to call upon a specific csv file and plot two columns form the file. I have successfully called upon those columns and converted irrelevant values to NaN. I am now attempting to plot the columns in a line graph to obtain a time series. I am getting an error that I need to convert to float which I tried but it gave me the error that the float must be a string or a number. I had to convert the values in the csv file from a string to a list to make irrelevant values nan, so now i have to switch them back to plot? Once the column is being read correctly by python, is the way in which I have plotted it correct?

import csv
import numpy as np
import matplotlib.pylab as plt
import pandas


def getColumn(filename, column):
    results = csv.reader(open(filename), dialect='excel')
    return [result[column] for result in results]

time = getColumn("C:\Users\dfmcg\Documents\Thesisfiles\ALL_GPMP_O3_Met\ASIS-MA.csv",1)

time = time[1:]
ozone = getColumn("C:\Users\dfmcg\Documents\Thesis files\ALL_GPMP_O3_Met\ASIS-MA.csv",2)
ozone = list(map(int,ozone[1:]))

for i in range (0,len(ozone)):
    if ozone[i] == -999:
        ozone[i] = np.nan
float(ozone)

x = ozone
y = time

plt.plot(x,y)
plt.show

ABBR DATE O3 SWS VWS SWD VWD SDWD TMP RH RNF SOL CASA-GD 07/01/2005 00 -999 -999 -999
CASA-GD 07/01/2005 01 -999 -999 -999
CASA-GD 07/01/2005 02 -999 -999 -999
CASA-GD 07/01/2005 03 -999 -999 -999
CASA-GD 07/01/2005 04 -999 -999 -999
CASA-GD 07/01/2005 05 -999 -999 -999
CASA-GD 07/01/2005 06 -999 -999 -999
CASA-GD 07/01/2005 07 -999 -999 -999
CASA-GD 07/01/2005 08 -999 -999 -999
CASA-GD 07/01/2005 09 -999 -999 -999
CASA-GD 07/01/2005 10 -999 -999 -999
CASA-GD 07/01/2005 11 -999 -999 -999

Can you check the type of the elements of your list with

print type(ozone[0])  

maybe then you can see where the error originates from

tldr comments: The ozone values were integer types, the included NaN values were floats. Seemingly you cannot plot two different types. This can be solved by setting everything to float

 [float(x) for x in ozone]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM