1

I currently have the following column:

0          [Joe]
1           John
2           Mary
3         [Joey]
4          Harry
5        [Susan]
6          Kevin

I can't seem to remove the [] with out making the rows with [] = NaN

To be clear I want the column to look like this:

0            Joe
1           John
2           Mary
3           Joey
4          Harry
5          Susan
6          Kevin

Can anyone help?

3 Answers 3

3

Your title seems to imply that some elements of your series are lists.

setup

s = pd.Series([['Joe'], 'John', 'Mary', ['Joey'], 'Harry', ['Susan'], 'Kevin'])
s

0      [Joe]
1       John
2       Mary
3     [Joey]
4      Harry
5    [Susan]
6      Kevin
dtype: object

option 1
apply with pd.Series

s.apply(pd.Series).squeeze()

0      Joe
1     John
2     Mary
3     Joey
4    Harry
5    Susan
6    Kevin
Name: 0, dtype: object
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

df['column_name'] = df['column_name'].apply(lambda x: str(x).strip("'[]") if type(x) == list else x)

4 Comments

AttributeError: 'list' object has no attribute 'strip' I think the lists within the column are causing issues. I need to address the multiple lists of length 1 within the column rather than just strip the []
Yes that worked! It returned the column with single quotes i.e. '' where there was previously []. To remove those I added .strip("''") to the end of your solution so it ended up working with :
df['column_name'] = df['column_name'].apply(lambda x: str(x).strip('[]').strip("''"))
@firetheRookie Don't have to use an additional strip. You can do that in 1 strip. strip("'[]") Updated my answer.
0

Why not just do s.astype(str).str.strip ("'[]'") or

s.map(lambda x: x if type(x) != list else x [0])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.