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

Categories

0 votes
4.3k views
in Technique[技术] by (71.8m points)

python - New Column Based on Last Delimiter Split

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"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...