Ytp
Ytp

Reputation: 1

Expand a list in a DataFrame

Lets say I have a list of numbers to concat. The results as follows:

                  A          B        ...        Z
    (1,a)        [1]        [2]
    (2,b)        [3]        [4]
    (3,c)        [5,6]      [7,8]
    (4,d)        [9]        [10]

But I wish to convert it into something more presentable in a excel sheet/csv, how can i convert the DataFrame into something like this:

                      A        B        ...        Z
    1        a        1        2
    2        b        3        4
    3        c        5        7
    3        c        6        8
    4        d        9        10

Am trying to avoid running through each row to print into a csv file. Is there a better method to convert the DataFrame?

Upvotes: 0

Views: 63

Answers (1)

Henry Yik
Henry Yik

Reputation: 22503

Use pd.Series.explode and reconstruct df from new index, finally concat:

s = df.apply(pd.Series.explode)

print (pd.concat([pd.DataFrame(s.index.tolist()),s.reset_index(drop=True)], axis=1))

   0  1  A   B
0  1  a  1   2
1  2  b  3   4
2  3  c  5   7
3  3  c  6   8
4  4  d  9  10

Upvotes: 1

Related Questions