When I try to make a histogram without the zero values, I get an error:
Traceback (most recent call last):.
I have a list of Beam_irradiance_DNI
values which include several zeroes. I can make histogram, but I don't want the zero values.
import matplotlib.pyplot as plt
import numpy as np
import csv
# Reading data from csv file
with open('Upington_DNI.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
Hour_of_year = []
Beam_irradiance = []
for row in readCSV:
hour = row[0]
DNI = row[1]
Hour_of_year.append(hour)
Beam_irradiance.append(DNI)
Hours_since00hrsJan1 = [float(Hour_of_year[c]) for c in range(1,len(Hour_of_year))]
Beam_irradiance_DNI=[float(Beam_irradiance[c]) for c in range(1,len(Beam_irradiance))]
plt.figure(3)
Beam_irradiance_DNI[ Beam_irradiance_DNI==0 ] = np.nan
plt.hist(Beam_irradiance_DNI, color="grey")
plt.title("Histogram for Beam irradiance - DNI")
plt.xlabel("Beam irradiance - DNI [W/m2]"); plt.ylabel("Probability of occurrence")
plt.show()
I dont know what is wrong here.
You can only perform logical indexing (data[data != 0]
) on a numpy.array
not a normal python list. If you want to remove values from a python list, you'll want to use a list comprehension to do that.
newvalues = [x for x in Beam_irradiance_DNI if x != 0]
The other alternative is to actually convert your python list to a numpy array.
nparray = np.array(Bean_irradiance_DNI)
Then you will be able to do the logical indexing you want to perform
nparray[nparray == 0] = np.nan
The other alternative is to not alter the array itself, and simply pass only the non-zero values to hist
plt.hist(Beam_irradiance_DNI[Beam_irradiance_DNI != 0], color="grey")
If you're still having issues with zeros, it's likely due to the fact that these numbers are stored as floating point numbers and their value isn't exactly zero. For this you would want to use the following condition to detect "zeros".
is_zero = np.absolute(Beam_irradiance_DNI) < np.finfo(float).eps
Beam_irradiance_DNI[is_zero] = np.nan
import numpy as np
Beam_irradiance_DNI = np.array(Beam_irradiance_DNI)
plt.hist(Beam_irradiance_DNI[Beam_irradiance_DNI>0], color="grey")
this should work because you only keep the elements which are above zero (Beam_irradiance_DNI>0
is a boolean mask used as index). In case you want to use this further save it as a variable but if you only want to exclude zeros for the histogram don't bother with redefining your variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With