简体   繁体   English

如何从 DataFrame 中拆分一列?

[英]How to split a column from a DataFrame?

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.我知道这可以使用 str.split() 轻松实现,但是当我拆分时,它应该返回 7 列,但它只返回第一列。

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这是我运行代码后 DataFrame 的样子: 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尝试使用ast.literal_eval然后explode

import ast 
df1['Genres'].map(ast.literal_eval).explode()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM