Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

pandas

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.

like image 497
Iceberg_Slim Avatar asked Mar 17 '20 12:03

Iceberg_Slim


People also ask

How do you rejoin a split string in Python?

Method: In Python, we can use the function split() to split a string and join() to join a string. the split() method in Python split a string into a list of strings after breaking the given string by the specified separator.

How do you split a series in Python?

The str. split() function is used to split strings around given separator/delimiter. The function splits the string in the Series/Index from the beginning, at the specified delimiter string.

What split () & join () method Why & Where it is used?

You can use split() function to split a string based on a delimiter to a list of strings. You can use join() function to join a list of strings based on a delimiter to give a single string.

How do you split multiple strings in Python?

Method 1: Split multiple characters from string using re. split() This is the most efficient and commonly used method to split multiple characters at once. It makes use of regex(regular expressions) in order to do this.


Video Answer


1 Answers

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)
like image 94
a_guest Avatar answered Oct 12 '22 12:10

a_guest