Created
August 5, 2016 19:07
-
-
Save anonymous/1a0728a5ca56b651853427e1cb8baf07 to your computer and use it in GitHub Desktop.
how to flatten nested list with pyrhon
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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