itthrill
itthrill

Reputation: 1376

Converting python list of delimited items in to a pandas data frame

I have a list like this where items are separated by ":".

   x=['john:42:engineer',
      'michael:29:doctor']

Is there an way to change this in to a data frame like below by defining columns Name, Age and Occupation?

    Name    Age Occupation
0   john    42  engineer
1   michael 29  doctor

Upvotes: 2

Views: 97

Answers (3)

BENY
BENY

Reputation: 323226

I will do

df = pd.Series(x).str.split(':',expand=True)
df.columns = ['Name','Age', 'Occupation']
df
Out[172]: 
      Name Age Occupation
0     john  42   engineer
1  michael  29     doctor

Upvotes: 4

footfalcon
footfalcon

Reputation: 619

Not sure this is the best approach, but...

x = ['john:42:engineer', 'michael:29:doctor']
x = [i.split(':') for i in x]
pd.DataFrame({'name': [i[0] for i in x], 'age': [i[2] for i in x], 'occupation': [i[1] for i in x]})

Output:

    name    age occupation
0   john    42  engineer
1   michael 29  doctor

Upvotes: 1

Quang Hoang
Quang Hoang

Reputation: 150735

You can just use split:

pd.DataFrame([y.split(':') for y in x], columns = ['Name','Age', 'Occupation'])

Output:

      Name Age Occupation
0     john  42   engineer
1  michael  29     doctor

Upvotes: 5

Related Questions