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?

2
  • 1
    try df.iterrows() Commented Jul 1, 2019 at 4:55
  • 1
    @YashKumarAtri No, don't try df.iterrows(). There's bad advice flying from every direction. Commented Jul 1, 2019 at 5:27

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Don't use apply(pd.Series) (you'll need to scroll to find it). pd.DataFrame(df['col'].tolist()) is always better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.