根据定界符垂直分割DataFrame

时间:2018-07-19 15:02:57

标签: python pandas dataframe data-manipulation data-cleaning

说我有这个DataFrame:

>>> import pandas as pd
>>> df = pd.DataFrame(['eggs, spam', 'lobster', 'eggs, lobster'], columns=['ingredients'])
>>> df
     ingredients
0     eggs, spam
1        lobster
2  eggs, lobster

我想基于定界符','拆分列“成分”。我想得到一个看起来像这样的DataFrame:

     ingredients
0     eggs
1     spam
2     lobster
3     eggs
4     lobster

我该如何实现?

1 个答案:

答案 0 :(得分:7)

使用 split stack

df.ingredients.str.split(', ', expand=True).stack().reset_index(drop=True)

0       eggs
1       spam
2    lobster
3       eggs
4    lobster
dtype: object