Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing Nones in a python array with zeroes

I've just joined two arrays of unequal length together with the command:

allorders = map(None,todayorders, lastyearorders)

where "none" is given where today orders fails to have a value (as the todayorders array is not as long).

However, when I try to pass the allorders array into a matplotlib bar chart:

 p10= plt.bar(ind, allorders[9],   width, color='#0000DD', bottom=allorders[8])

..I get the following error:

TypeError: unsupported operand type(s) for +=: 'int' and 'NoneType'

So, is there a way for matplotlib to accept none datatypes? if not, how do I replace the 'Nones' with zeroes in my allorders array?

If you can, as I am a Python newbie (coming over from the R community), please provide detailed code from start to finish that I can use/test.

like image 500
user1784454 Avatar asked Aug 23 '26 13:08

user1784454


2 Answers

With numpy:

import numpy as np
allorders = np.array(allorders)

This creates an arrray of objects due to the Nones. We can replace them with zeros:

allorders[allorders == None] = 0

Then convert the array to the proper type:

allorders.astype(int)
like image 150
Jay Avatar answered Aug 26 '26 03:08

Jay


Use a list comprehension:

allorders = [i if i[0] is not None else (0, i[1]) for i in allorders]
like image 40
Martijn Pieters Avatar answered Aug 26 '26 03:08

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!