1

I would like to know whether I can get some help in "translating" a multi dim list in a single column of a frame in pandas.

I found help here to translate a multi dim list in a column with multiple columns, but I need to translate the data in one

Suppose I have the following list of list

x=[[1,2,3],[4,5,6]]

If I create a frame I get

frame=pd.Dataframe(x)

0  1  2
1  2  3
4  5  6

But my desire outcome shall be

0
1
2
3
4
5
6

with the zero as column header.

I can of course get the result with a for loop, which from my point of view takes much time. Is there any pythonic/pandas way to get it?

Thanks for helping men

Sociopath
  • 13,068
  • 19
  • 47
  • 75
SMS
  • 348
  • 2
  • 13

3 Answers3

5

You can use np.concatenate

x=[[1,2,3],[4,5,6]]

frame=pd.DataFrame(np.concatenate(x))
print(frame)

Output:

    0
0   1
1   2
2   3
3   4
4   5
5   6
Sociopath
  • 13,068
  • 19
  • 47
  • 75
4

First is necessary flatten values of lists and pass to DataFrame constructor:

df = pd.DataFrame([z for y in x for z in y])

Or:

from  itertools import chain

df = pd.DataFrame(list(chain.from_iterable(x)))

print (df)
   0
0  1
1  2
2  3
3  4
4  5
5  6
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • wow thank you very much :) Too stupid to check for flattening or numpy order. thanks again :) – SMS Nov 28 '19 at 09:59
1

If you use numpy you can utilize the method ravel():

pd.DataFrame(np.array(x).ravel())
Mykola Zotko
  • 15,583
  • 3
  • 71
  • 73