danielecook
9/21/2018 - 11:16 AM

unnest pandas df

unnest pandas df

# https://benjcunningham.org/blog/unnest-list-columns-in-pandas.html
import pandas as pd

def unnest(df, col):
    unnested = (df.apply(lambda x: pd.Series(x[col]), axis=1)
                .stack()
                .reset_index(level=1, drop=True))
    unnested.name = col
    return df.drop(col, axis=1).join(unnested)