python - pandas - split string and take each couple -
i have dataframe looks that:
ids name john 1,4,8 eric 2,9,17 paul 41,72,78,100 i need take every combination ids , assign new raw, output df should that:
ids name john 1,4 john 1,8 john 4,8 eric 2,9 eric 2,17 eric 9,17 paul 41,72 paul 41,78 paul 41,100 paul 72,78 paul 72,100 paul 78,100 i tried several ways none of them start close need.
let's use combinations itertools, pd.series, stack, , reset_index:
from itertools import combinations df.ids.apply(lambda x:pd.series(list(combinations(x.split(','),2))))\ .stack()\ .reset_index(level=1, drop=true) output:
name john (1, 4) john (1, 8) john (4, 8) eric (2, 9) eric (2, 17) eric (9, 17) paul (41, 72) paul (41, 78) paul (41, 100) paul (72, 78) paul (72, 100) paul (78, 100) dtype: object
Comments
Post a Comment