Reputation: 461
I have following dataset:
Name Codes
0 Tom a1,a2,a3
1 nick a1,b2,b3
2 krish a1,b2,c3
3 jack a5,c3,b1
How do I convert Codes
to be a list inside my data frame column?
I need the following result:
Name Codes
0 Tom [a1,a2,a3]
1 nick [a1,b2,b3]
2 krish [a1,b2,c3]
3 jack [a5,c3,b1]
Thank you!
Upvotes: 0
Views: 39
Reputation: 2405
A simple str.split(...)
call is sufficient
>>> df.Codes.str.split(",")
0 [a1, a2, a3]
1 [a1, b2, b3]
2 [a1, b2, c3]
3 [a5, c3, b1]
Upvotes: 1
Reputation: 565
The most efficient way would be as follows:
df['Codes'] = df['Codes'].str.split()
Its usually a good idea to favor built in functions when using pandas. These will usually have very efficient implementations in cython.
A more flexible, but slower solution would be to apply an arbitrary python function -
df['Codes'] = df['Codes'].apply(lambda x: x.split())
Upvotes: 1