ThoseKind ThoseKind - 4 months ago 6
Python Question

Replacing ' ' Values in a List with '0'

I have a few

.csv
files that contain
NULL
values that are viewed as empty in the table. For example:

ID Volts Current Watts
0 383 0
1 383 1 383
2 382 2 764


This
.csv
file is input into my program and converted to a list like this:

with open(inputPath + file) as inFile:
csvFile = csv.reader(inFile)
for row in csvFile:
removeNull(row)
print(row)


which essentially takes each row in
csvFile
and turns it into a list of values that looks something like this:

['0', '383', '', '0']
,
['1', '383', '1', '383]
, etc.

Note that the
NULL
values are now just empty strings,
''
.


Then in relation to the snipet of the program above
removeNull()
is defined as:

def removeNull(row):
nullIndex = row.index('')
row.remove('')
newRow = row.insert(nullIndex, '0')
return newRow


which looks through the list (aka row) for empty strings,
''
, and notes their index as
nullIndex
. Then removes the empty string at said index, replaces it with
'0'
and returns the edited list.

Question: What exactly is wrong with my
removeNull()
function that causes it to only replace the first empty string,
''
, in a list? And how can I fix it so that it works for all empty strings in a list?

For clarification, a table like this with only one
NULL
value per row, or empty string once converted to a list, works just fine.

ID Volts Current Watts
0 383 0
1 383 1 383
2 382 2 764


['0', '383', '', '0']
works fine.

However if I have a table like this, with multiple
NULL
values per row, it will only replace the first empty string in the converted list and do nothing with the rest.

ID Volts Current Watts
0 0
1 383 1 383
2 382 2 764


['0', '', '', '0']
does not work fine.

Answer

Because list.index only returns index of the first occurrence of the item in the list. You can instead use a list comprehension on each row to do the replacement:

def removeNull(row):
    return ['0' if i=='' else i for i in row]
    #       |<- ternary op. ->|  

The ternary operator in the list comprehension replaces blank strings with '0' while others are returned as they are.

On a side note, your function does not modify row in-place, therefore, you will need to assign the return value of the function to row:

for row in csvFile:
    row = removeNull(row)
    print(row)
Comments