Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am getting an index error while trying to use a lambdas function like below... I am trying to extract just the last 2-3 characters from the string based on a space as a delimiter. Why would this not work?

Error:

Traceback (most recent call last):
  File "C:Users
obert.carmodyOneDrive - AccenturePythonGlobal T&O Learning.py", line 116, in <module>
    report_demand['Industry'] = report_demand['Industry'].apply(lambda x: x.rsplit(' ', 1)[1])
  File "C:Python38libsite-packagespandascoreseries.py", line 3848, in apply
    mapped = lib.map_infer(values, f, convert=convert_dtype)
  File "pandas\_libslib.pyx", line 2329, in pandas._libs.lib.map_infer
  File "C:Users
obert.carmodyGlobal T&O Learning.py", line 116, in <lambda>
    report_demand['Industry'] = report_demand['Industry'].apply(lambda x: x.rsplit(' ', 1)[1])
IndexError: list index out of range

Code:

report_demand['Industry'] = report_demand['Industry'].astype(str)
report_demand['Industry'] = report_demand['Industry'].apply(lambda x: x.rsplit(' ', 1)[1])

example string: "Newport Chicago IL" or "Kingston Jamaica USR"

expected output: "IL" and "USR"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.8k views
Welcome To Ask or Share your Answers For Others

1 Answer

If you are looking for the last element of the list, then you would need to use [-1] instead of [1]. Furthermore, there's no need for apply + lambda, you can use .str.split(). Try with the following:

report_demand['Industry'] = report_demand['Industry'].str.split().str[-1]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...