Reputation: 1376
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
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
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
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