0

I have a list in which I am trying to replace empty strings with 0. Is there a way to do this other than iterating through each item in the list?

Here's a smaller example of what my list is like:

testlist=['',18.0,'','',0,15,8.0]

In Matlab, I know I could do something like this:

testlist[testlist=='']=0

but this only seems to change the first value (even if its something other than an empty string).

Pac0
  • 21,465
  • 8
  • 65
  • 74
Deborah Paul
  • 81
  • 1
  • 9
  • Possible duplicate of [Replace values in list using Python](https://stackoverflow.com/questions/1540049/replace-values-in-list-using-python) – Fred Larson Apr 04 '18 at 21:09
  • boolean indexing is part of numpy not normal python lists `import numpy;testlist=numpy.array(['',18.0,'','',0,15,8.0]);testlist[testlist=='']=0` – Joran Beasley Apr 04 '18 at 21:10

2 Answers2

2

In python you can use a list comprehension:

A = ['', 18.0, '', '', 0, 15, 8.0]

Here this subsequent A has the '' values replaced with 0's.

A = [x if x != '' else 0 for x in A]
eric
  • 1,029
  • 1
  • 8
  • 9
0

You can do this in several ways:

The first way is using a list comprehension like the other answer does:

a = ['',18.0,'','',0,15,8.0]
b = [x if x != '' else 0 for x in a]

This reads like: 'Make an array b with each element x of a for which if x is not '' then put x, else put 0'.

There is also an awesome library called numpy which utilizes a syntax that looks like the syntax from Matlab you are referring to:

import numpy as np
a = ['',18.0,'','',0,15,8.0]
# Create a numpy array from the list
b = np.array(a)
b[b == ''] = 0
print(b)
>>> array(['0', '18.0', '0', '0', '0', '15', '8.0'],
  dtype='<U4')

The array is now an array of strings, which you can convert to a float or something else using np.ndarray.astype(type).

Considering you've referred Matlab's syntax, I suggest having a look at numpy. When writing scripts in Python, you will notice numpy and Matlab share a lot of syntax.

brvh
  • 264
  • 3
  • 15