Converting list column to string in pandas

Viewed 75

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

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

You can join:

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

Or:

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

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')

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

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)
Related