Home > Enterprise >  Removing square brackets from pandas series. *multiple list elements
Removing square brackets from pandas series. *multiple list elements

Time:05-25

I have all the elements in pandas.series in square brackets. I need to remove the square brackets only. Notice that we have list with 2 or more elements occasionally and it has to be preserved. *Some of the solutions online were stripping it to first index.

I am in dire need for a solution. Please..

ecg_id
41         [CD]
42       [NORM]
43       [NORM]
44       [NORM]
45    [CD, HYP]
46       [NORM]
47       [NORM]
48       [STTC]
49         [CD]
50     [CD, MI]
51       [NORM]
52         [CD]
53       [NORM]
54       [STTC]
55       [NORM]

CodePudding user response:

You can apply a vectorized version of the builtin str.strip, str.rstrip (right side strip), and str.lstrip (left side strip) using the pandas.Series.str string methods:

Brackets on either side of each string element can be removed with the following:

s.str.lstrip('[').str.rstrip(']')

CodePudding user response:

It looks like all the values inside your Series object are strings. So you can use the pandas.Series.transform to change those from lists into raw (comma-separated) strings:

>>> series = pd.Series(data=[['a'], ['b','c'], ['d']])
>>> series
0       [a]
1    [b, c]
2       [d]
dtype: object
>>> series.transform(lambda x: ','.join(x))
0      a
1    b,c
2      d
dtype: object
  • Related