2

I have dataframe df like this :

    date        item
    2019-03-29  [book,pencil]
    ...

I want to get every item in list using loop. this is what I've tried:

    for i in range(len(df)):
        for x in df['attributeName'][i]:
            print(x)

But i got every single character. The desired output is:

    book
    pencil

How do I solve this problem?

Emma
  • 27,428
  • 11
  • 44
  • 69
elisa
  • 489
  • 5
  • 13

1 Answers1

3
df2['item'].apply(pd.Series).unstack().reset_index(drop=True)

A better alternative.. A Common Pitfall: Exploding Columns of Lists

pd.DataFrame(df2['item'].tolist()).unstack().reset_index(drop=True)

Output

0      book
1    pencil
dtype: object
iamklaus
  • 3,720
  • 2
  • 12
  • 21
  • 2
    [Don't use `apply(pd.Series)`](https://stackoverflow.com/questions/54432583/when-should-i-ever-want-to-use-pandas-apply-in-my-code) (you'll need to scroll to find it). `pd.DataFrame(df['col'].tolist())` is always better. – cs95 Jul 01 '19 at 05:02