Last active
April 18, 2019 20:08
-
-
Save michaelsilverstein/e1f6df46575aa139e5bbf87281ae13c9 to your computer and use it in GitHub Desktop.
Transform a list within within a column to a df indicating membership of each thing
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 | |
# Data | |
data = [['T1', ['Round', 'Red']], | |
['T2', ['Round', 'Green']], | |
['T3', None], | |
['T4', ['Square']]] | |
# Make dataframe and set index | |
df = pd.DataFrame(data, columns=['thing', 'desc']).set_index('thing') | |
# "Explode" list | |
exploded = df.desc.apply(pd.Series) | |
# Stack all options (this is melting, but does for all columns->Series) | |
stacked = exploded.stack().reset_index('thing', name='values') | |
# Indicate what's present | |
stacked['present'] = True | |
# Pivot (all things that are present will be True, everything else will be NaN) and fill nulls with False | |
stacked.pivot('thing', 'values', 'present').fillna(False) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output