0

I was recently trying to read in a csv, of which one of the columns is serialized as list strings. Using ast.literal_eval usually converts the string to an actual list. In this case, even though we check whether a is a list or not, we get back an error saying None type is non subscriptable.

Code:

def generate(name):
    df = pd.read_csv(name)
    df['column'] = df['column'].apply(lambda x: literal_eval((x))) # all x should become list
    for a in df['column']:
        if a and isinstance(a, list):
            print(a)[0]
        else:
            print('jey')

Error message (the first list is printed)

[0.0, 0.0, 0.014, 0.0]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-34-d84f295beae6> in <module>
----> 1 generate('parameter_vv/perimeter_log.csv')

<ipython-input-33-e9ee10a439d4> in generate(name)
      4     for a in df['column']:
      5         if a and isinstance(a, list):
----> 6             print(a)[0]
      7         else:
      8             print('jey')

TypeError: 'NoneType' object is not subscriptable
1
  • 3
    print returns None. I think you wanted print(a[0]) Commented Jan 30, 2020 at 16:19

2 Answers 2

1

print(a) return None and you see this error when try to do print(a)[0].

I suppose you want to do this instead:

print(a[0])
Sign up to request clarification or add additional context in comments.

Comments

1

You have to use print(a[0]) instead of print(a)[0].


print() returns None, so print(a)[0] try to get element 0 from None, this is the error you get.

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.