Jesh Kundem
Jesh Kundem

Reputation: 974

Replace an empty string in a list with NaN

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

Upvotes: 2

Views: 17322

Answers (4)

Nunya
Nunya

Reputation: 73

Here's another option that uses the isinstance() method. Using basestring works for both plain strings and Unicode strings.

[np.nan if isinstance(x, basestring) else x for x in a]

Upvotes: 0

Taohidul Islam
Taohidul Islam

Reputation: 5414

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].

Upvotes: 2

Lix
Lix

Reputation: 47966

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.

Upvotes: 1

Mathieu
Mathieu

Reputation: 5746

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...

Upvotes: 5

Related Questions