python - Expand a column holding iterables into rows -


say have dataframe following:

df = pd.dataframe({'baz': ['yes','fine'], 'foo': [['a', 'b', 'c'], ['s', 'r']]},                     index=['w1', 'w2'])  > df      baz        foo w1   yes   [a, b, c] w2   fine     [s, r] 

how can expand column foo? result should be, in case:

> df     baz  foo w1  yes        yes    b     yes    c w2  fine   s     fine   r 

you can rebuild dataframe extracting values , recreating index:

result = [] [result.extend(zip(([df.baz[i]])*len(df.foo[i]), df.foo[i])) in range(len(df.baz))] index = [[df.index[i]]*len(df.foo[i]) in range(len(df.baz))] index = [item sublist in index item in sublist] # flatten   final = pd.dataframe(result,index=index, columns = df.columns) # final result 

result be:

   baz foo w1   y   w1   y   b w1   y   c w2   z   s w2   z   r 

Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -