Instantly share code, notes, and snippets.

What would you like to do?
how to flatten nested list with pyrhon
import pandas as pd
from 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]
# 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