Skip to content

Instantly share code, notes, and snippets.

Created August 5, 2016 19:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/1a0728a5ca56b651853427e1cb8baf07 to your computer and use it in GitHub Desktop.
Save anonymous/1a0728a5ca56b651853427e1cb8baf07 to your computer and use it in GitHub Desktop.
how to flatten nested list with pyrhon
import pandas as pd
from collections.abc import Iterable
def is_iter(iter):
return isinstance(iter, Iterable) and not (isinstance(iter, str) and len(iter) == 1)
def flatten(nested_iter):
for element in nested_iter:
yield from flatten(element) if is_iter(element) else [element]
df = pd.DataFrame([['A', 1],['B', 3], ['C', 1],['D', 1],['E', 2]], columns=['category', 'frequency'])
mylist = [reduce(lambda x,y: [x]*y, l) for l in df[['category', 'frequency']].values]
print(list(flatten(mylist)))
# result.
# >>> ['A', 'B', 'B', 'B', 'C', 'D', 'E', 'E']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment