说我有这个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
我该如何实现?
答案 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