I am trying to split a column from a Data frame. I know this can be easily achieved using str.split(), but when I split it should return 7 columns, but it only return the first column.
This is the column I am trying to split:
print(df1['Genres'])
0 ['Drama']
1 ['Crime', 'Drama']
2 ['Crime', 'Drama']
3 ['Action', 'Crime', 'Drama', 'Thriller']
4 ['Crime', 'Drama']
...
And this is my code so far:
df1 = pd.DataFrame(pd.read_csv('Dataset01.csv'))
df1['Genres'] = df1['Genres'].map(lambda x: x.lstrip("["))
df1['Genres'] = df1['Genres'].map(lambda x: x.rstrip("]"))
df1['Genres'] = df1['Genres'].str.replace("'", '')
df1['Genres'] = df1['Genres'].str.split(",", expand=True)
df1
I only get the column with the first values:
print(df1['Genres'])
0 Drama
1 Crime
2 Crime
3 Action
4 Crime
...
This is how the DataFrame looks like after I run the code: DataFrame
As you can see it only returns one column
Is there something else I can do to split the columns? Or is there something I can do to fix that?
Thanks
Try with ast.literal_eval
then explode
import ast
df1['Genres'].map(ast.literal_eval).explode()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.