Python: How to split and re-join first and last item in series of strings

Iceberg_Slim :

I have a Series of strings, the series looks like;

Series
"1, 2, 6, 7, 6"
"1, 3, 7, 9, 9"
"1, 1, 3, 5, 6"
"1, 2, 7, 7, 8"
"1, 4, 6, 8, 9"
"1"

I want to remove all elements apart from the first and last, so the output would look like;

Series
"1, 6"
"1, 9"
"1, 6"
"1, 8"
"1, 9"
"1"

To use Split(), do I need to loop over each element in the series? I've tried this but can't get the output I'm looking for.

a_guest :

You can use split and rsplit to get the various parts:

result = [f"{x.split(',', 1)[0]},{x.rsplit(',', 1)[1]}" if x.find(',') > 0 else x
          for x in strings]

If strings is a pd.Series object then you can convert it back to a series:

result = pd.Series(result, index=strings.index)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=297257&siteId=1
Recommended