Reputation: 63
I have a column whose values are lists. as you see in the following image: columns image
I want the "sequence_movie_ids" column which is a list to be split into two columns, a column comprised of all the values except the last element of the list and another comprised the last element of the list. How can I do this?
Upvotes: 2
Views: 71
Reputation: 41487
If type(df['sequence_movie_ids'].iloc[0])
returns list
:
Either use the Series.str
accessor to split the lists:
df['all_but_last'] = df['sequence_movie_ids'].str[:-1]
df['only_last'] = df['sequence_movie_ids'].str[-1]
Or use Series.apply
:
df['all_but_last'] = df['sequence_movie_ids'].apply(lambda x: x[:-1])
df['only_last'] = df['sequence_movie_ids'].apply(lambda x: x[-1])
If type(df['sequence_movie_ids'].iloc[0])
returns str
, that means they are strings that just look like lists.
In that case, first parse them into real lists using ast.literal_eval
:
from ast import literal_eval
df['sequence_movie_ids'] = df['sequence_movie_ids'].apply(literal_eval)
And then use the all_but_last
and only_last
code from above.
Upvotes: 2
Reputation: 43
if its a real list and not string, you can do like this:
a = sequence_movie_ids[:len-1]
and b = sequence_movie_ids[len-1]
Upvotes: 1