bismo
bismo

Reputation: 1439

How to convert a column of lists to a column of strings python

I am accessing data from an API and it returned a column of data that consists one single or two item lists, like so:

EDIT: This is a pandas series.

['WR'],
 ['RB'],
 ['QB'],
 ['QB'],
 ['TE'],
 ['TE'],
 ['TE'],
 ['WR', 'RB'],
 ['QB'],
 ['WR'],
 ['WR'],
 ['WR'],
 ['TE'],
 ['TE'],
 ['TE'],
 ['WR'],
 ['WR'],
 ['WR'],
 ['WR'],
 ['RB'],
 ['RB'],
 ['WR', 'RB'],
 ['WR']
...

And so on. What I would like to do is to simply convert each list to a string, like so:

'WR',
 'RB',
 'QB',
 'QB',
 'TE',
 'TE',
 'TE',
 'WR, RB',
...

And so on. I tried .explode() but this isn't exactly what I want because I don't want the lists with two items to make a new row for the second item. I also tried simply indexing it using [1:-1] but obviously that didn't work since the brackets aren't characters in the string. I appreciate any help. Thanks!

Upvotes: 4

Views: 98

Answers (3)

BENY
BENY

Reputation: 323226

Let us try

s.str.join(',')

Out[249]: 
0       RB
1       QB
2       QB
3    WR,TE
dtype: object

Upvotes: 6

Scott Boston
Scott Boston

Reputation: 153460

Try this:

import pandas as pd
import numpy as np

s = pd.Series([['RB'],['QB'],['QB'], ['WR','TE']])

s.map(', '.join)

Output:

0        RB
1        QB
2        QB
3    WR, TE
dtype: object

Upvotes: 5

Kuldip Chaudhari
Kuldip Chaudhari

Reputation: 1112

Try:

List=[', '.join(r) for r in List]

Upvotes: 3

Related Questions