Skip to content
Advertisement

How do you remove corresponding x values of missing y-data from lists?

JavaScript

When I plot this graph the y-axis looks very off. Realising I need to remove the “” spaces in the list, I tried this method:

JavaScript

This showed me a dimensional error. I don’t know how to only extract the corresponding values of x to the y values.

Advertisement

Answer

You can use pandas’ pd.to_numeric(..., errors='coerce') to convert each of the strings in the lists to ‘nan’. (Numpy’s np.genfromtxt(np.array(..., dtype=str)) does something similar, but also removes the empty strings).

nan values will be skipped while plotting. Matplotlib puts its list of x-values next to the corresponding y-values, e.g. 2011.005, 1.4356 for the first pair and 2012.6543, np.nan for the second. Each pair that has one or two nan values will not be plotted.

Here is some example code:

JavaScript

example plot

It is unclear how your csv file looks like. The following example supposes the file looks like csv_as_str. (StringIO is a function that lets you mimic a file with a string, so it is easier to add to a post. Reading from a file would just be df = pd.read_csv('your_file.csv').)

JavaScript

Then the dataframe already has nan for the empty spots:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement