Question

Say I have a DataFrame like the 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 I expand the column foo? The result should be, in this case:

> df
    baz  foo
W1  yes    a
    yes    b
    yes    c
W2  fine   s
    fine   r
Was it helpful?

Solution

You can rebuild a DataFrame by extracting values and recreating index:

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

final = pd.DataFrame(result,index=index, columns = df.columns) # final result

result will be:

   baz foo
W1   y   a
W1   y   b
W1   y   c
W2   z   s
W2   z   r
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top