Skip to content
Minsing Log
Go back

English Edition

Flattening

Programming & CS

Situation

I solved the task of flattening a pandas dataframe containing list elements into a list using list comprehension. However, this abuses list comprehension and results in code that is much less readable.

[passage for lst_passage in make_passages['passages'] for passage in lst_passage]

Solutions

  1. Use itertools
import itertools

passages = list(itertools.chain.from_iterable(make_passages['passages']))
  1. Unpacking (using *)
passages = list(*passage for passage in make_passages['passages'])
  1. Functions
def flatten_list(nested_list):
   return [item for sublist in nested_list for item in sublist]

passages = flatten_list(make_passages['passages'])

Follow the journey

Get new posts by email.

Short, honest notes on building, startups, learning, failures, and retrospectives, for readers who follow the journey rather than pass through from search.

The newsletter is coming soon. Until then, follow via RSS or email me to get notified.


Share this post:

Comments

Sign in with GitHub to leave a comment.


Previous Post
Creating multiple dataframes with apply
Next Post
apply function