Home > Net >  Python getting part of string based on condtion
Python getting part of string based on condtion

Time:11-25

Hi I am pretty new to Python and is currently looking for a way to effectively get a part of a string from a column based on a condition.

I currently have a column with the address. It looks something like this.

data = {'addr': ['Seoul Gangnam Apgujeong 38-5', 'Seoul Songpa Jamsil 40-1 5-1302', 'Jeju Jeju Aewol 31-5', 'Busan Haeuondae Centum 70-1 7-141']}

I want to extract the second and the third value of the string. So the result should look something like this

data = {'addr': ['Gangnam Apgujeong', 'Songpa Jamsil', 'Jeju Aewol', 'Haeuondae Centum']}

Any sort of feedback would be appreciated!! Thank you in advance!!

CodePudding user response:

You can use list comprehension with split, slicing, and join:

data = {'addr': ['Seoul Gangnam Apgujeong 38-5', 'Seoul Songpa Jamsil 40-1 5-1302', 'Jeju Jeju Aewol 31-5', 'Busan Haeuondae Centum 70-1 7-141']}
output = {'addr': [' '.join(s.split()[1:3]) for s in data['addr']]}
print(output) # {'addr': ['Gangnam Apgujeong', 'Songpa Jamsil', 'Jeju Aewol', 'Haeuondae Centum']}
  • Related