-2

I have following pandas series:

0        [[1, 11283, 01, 5], [2,5, 1, 1]]
1        [[6, 33, 21, 2], [11283, 01, 5,1]] 
2        [[8430, 01, 2, 2],[2, 1, 1, 1]]

I need to save this as csv but csv rows should be something similar to following:

1, 11283, 01, 5
2,5, 1, 1
6, 33, 21, 2
11283, 01, 5,1
8430, 01, 2, 2
2, 1, 1, 1
user2805885
  • 1,683
  • 1
  • 14
  • 17

2 Answers2

4

Try:

df = pd.Series([[[1, 11283, 1, 5], [2,5, 1, 1]], 
                [[6, 33, 21, 2], [11283, 1, 5,1]], 
                [[8430, 1, 2, 2],[2, 1, 1, 1]]])

df.apply(pd.Series).stack().reset_index(drop=True)

As @jezrael, @coldspeed, and many other pandas gods have suggested use the following over apply(pd.Series):

pd.DataFrame(df.values.tolist()).stack().reset_index(drop=True)

Output:

0    [1, 11283, 1, 5]
1        [2, 5, 1, 1]
2      [6, 33, 21, 2]
3    [11283, 1, 5, 1]
4     [8430, 1, 2, 2]
5        [2, 1, 1, 1]
dtype: object
Scott Boston
  • 147,308
  • 15
  • 139
  • 187
1

If you don't care about 01 becoming 1:

df = pd.Series([[[1, 11283, 1, 5], [2,5, 1, 1]], 
                [[6, 33, 21, 2], [11283, 1, 5,1]], 
                [[8430, 1, 2, 2],[2, 1, 1, 1]]])
flat_list = [item for sublist in df.tolist() for item in sublist if item not in (',','[',']')]
pd.DataFrame(flat_list).to_csv('your_path')
Yuca
  • 6,010
  • 3
  • 22
  • 42