Created
March 26, 2019 04:58
-
-
Save vietvudanh/60a20a3a087c95d8a8c420eac15b4e7f to your computer and use it in GitHub Desktop.
explode list-type cell in pandas
This file contains hidden or 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
# credited to: https://stackoverflow.com/a/40449726 | |
''' | |
df | |
var1 var2 var3 | |
0 [a, b, c] 1 XX | |
1 [d, e, f, x, y] 2 ZZ | |
''' | |
lst_col = 'var1' | |
pd.DataFrame({ | |
col:np.repeat(df[col].values, df[lst_col].str.len()) | |
for col in df.columns.difference([lst_col]) | |
}).assign(**{lst_col:np.concatenate(df[lst_col].values)})[df.columns.tolist()] | |
''' | |
var1 var2 var3 | |
0 a 1 XX | |
1 b 1 XX | |
2 c 1 XX | |
3 d 2 ZZ | |
4 e 2 ZZ | |
5 f 2 ZZ | |
6 x 2 ZZ | |
7 y 2 ZZ | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment