0

I have DataFrame with list in one column and would like to append each list member as a new line. Here an example:

import pandas as pd
df = pd.DataFrame({'a': ['fruit','vegetable'], 'b': [['orange', 'banana'], ['apple']]})
df

    a          b
0   fruit      [orange, banana]
1   vegetable  [carrot]

and the result should be:

    a          b
0   fruit      [orange]
1   vegetable  [carrot]
2   fruit      [banana]

I know how to do it with loop (itertuples or iterrows) but I wonder if there's some more pythonic way than this:

for r in df[df['b'].str.len()>1].itertuples():
    for item in r.b:
        df = df.append({'a': r.a, 'b': [item]}, ignore_index=True)
df = df[df['b'].str.len()<2]
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Lukas
  • 2,034
  • 19
  • 27

0 Answers0