Pandas: Create several rows from column that is a list -
let's have this:
df = pd.dataframe({'key':[1,2,3], 'type':[[1,3],[1,2,3],[1,2]], 'value':[5,1,8]}) key type value 1 [1, 3] 5 2 [1, 2, 3] 1 3 [1] 8
where 1 of columns contains list of items. create several rows each row contains multiple types.
ontaining this:
key type value 1 1 5 1 3 5 2 1 1 2 2 1 2 3 1 3 1 8
i've been playing apply axis=1 can't find way return more 1 row per row of dataframe. extracting different 'types' , looping-concatenating seems ugly.
any ideas? thanks!!!
import itertools import pandas pd import numpy np def melt_series(s): lengths = s.str.len().values flat = [i in itertools.chain.from_iterable(s.values.tolist())] idx = np.repeat(s.index.values, lengths) return pd.series(flat, idx, name=s.name) melt_series(df.type).to_frame().join(df.drop('type', 1)).reindex_axis(df.columns, 1)
setup
df = pd.dataframe({'key':[1,2,3], 'type':[[1,3],[1,2,3],[1,2]], 'value':[5,1,8]}) df
Comments
Post a Comment