2

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
1
  • 3
    a = ["nan" if x == '' else x for x in a] ? Commented Jun 26, 2018 at 14:51

4 Answers 4

5

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

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.

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.