Replace an empty string in a list with NaN

10,631

Solution 1

It is working but you are simply running it without assigning the output to any location. Change the line with:

fl[2] = ["nan" if x == '' else x for x in a]

Or maybe:

a = ["nan" if x == '' else x for x in a]

Depending on where you want to store it...

Solution 2

You're creating this ["nan" if x == '' else x for x in a] list, but you're not assigning it! Your code should be like a= ["nan" if x == '' else x for x in a].

Solution 3

The output of list comprehension is a new list - what you'll need to do is override your existing list (or create a new one to hold the results)

a = ["nan" if x == '' else x for x in a]

I believe that the reason you though it was working in a standalone script is that when you execute the list comprehension as-is, python will print the list to the screen, but if you want to use this new list, you'll need to save it to a variable.

Share:
10,631

Related videos on Youtube

Jesh Kundem
Author by

Jesh Kundem

Updated on June 04, 2022

Comments

  • Jesh Kundem
    Jesh Kundem almost 2 years

    I am trying to replace an empty string in a list with a known string (say 'NAN'). I am using the following command

    a = ['','','asdf']    
    ["nan" if x =='' else x for x in a]
    

    The code is working, when it is used standalone, however when I am trying to employ it in my main code, it is not working. My main code is as follows:

    data = [ ('plant_data.xlsx', 0, []),('sorg.xlsx', 1, ['','','asdf'])]#,('sloc.xlsx', 1, ['307-040N'])];
    
    
    for fl in data:
        filename = fl[0];
        filename = filename[:-5];
    
        f = open('IC1_Results\%s.txt' %filename,'w');
    
        if fl[1] == 0:
            f.write("All Part Numbers exist");
            f.close()
    
        elif fl[1] == 1:
            a = fl[2];
            print type(a)
    
            ["nan" if x == '' else x for x in a]
    
            print fl[2],a
    
    • Rakesh
      Rakesh almost 6 years
      a = ["nan" if x == '' else x for x in a] ?