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

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


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)


You can use pandas vectorized split and then apply method:

import pandas as pds = pd.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, 2, 6, 8, 8"])s_split = s.str.split(',')r = s_split.apply(lambda r:','.join([r[0], r[-1]]))r0    1, 61    1, 92    1, 63    1, 84    1, 95    1, 8dtype: object


Try

[i.split()[0]+i.split()[-1] for i in series.str.split('\n')].join('\n')