2

I have a df called df like so. The tag_position is either a string or list. but I want them to be all strings. How can i do this? I also want to remove the white space at the end.

input

id  tag_positions
1   center
2   right
3   ['left']
4   ['center ']
5   [' left']
6   ['right']
7   left

expected output

id  tag_positions
1   center
2   right
3   left
4   center
5   left
6   right
7   left

5 Answers 5

5

You can explode and then strip:

df.tag_positions = df.tag_positions.explode().str.strip()

to get

   id tag_positions
0   1        center
1   2         right
2   3          left
3   4        center
4   5          left
5   6         right
6   7          left
Sign up to request clarification or add additional context in comments.

Comments

3

You can join:

df['tag_positions'].map(''.join)

Or:

df['tag_positions'].str.join('')

Comments

1

Try with str chain with np.where

df['tag_positions'] = np.where(df['tag_positions'].map(lambda x : type(x).__name__)=='list',df['tag_positions'].str[0],df['tag_positions'])

Also my favorite explode

df = df.explode('tag_positions')

1 Comment

this doesn't work for the ones that aren't a list
1

you can convert with apply method like this

df.tag_positions = df.tag_positions.apply(lambda x : ''.join(x) if type(x) == list else x)

if all the lists have a length of 1 you can do this also:

df.tag_positions = df.tag_positions.apply(lambda x : x[0] if type(x) == list else x)

Comments

1

You can use apply and check if an item is an instance of a list, if yes, take the first element. and then you can just use str.strip to strip off the unwanted spaces.

df['tag_positions'].apply(lambda x: x[0] if isinstance(x, list) else x).str.strip()

OUTPUT

Out[42]: 
0    center
1     right
2      left
3    center
4      left
5     right
6      left
Name: 0, dtype: object

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.