Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert list of lists into single column of pandas df

Tags:

python

pandas

I am trying to place multiple lists into a single column of a Pandas df. My list of lists is very long, so I cannot do so manually.

The desired out put would look like this:

list_of_lists = [[1,2,3],[3,4,5],[5,6,7],...]
df = pd.DataFrame(list_of_lists)
>>> df
    0
0   [1,2,3]
1   [3,4,5]
2   [5,6,7]
3   ...

Thank you for the assistance.

like image 568
user3155053 Avatar asked Feb 22 '16 22:02

user3155053


2 Answers

You can assign it by wrapping it in a Series vector if you're trying to add to an existing df:

In [7]:
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randn(5,3), columns=list('abc'))
df

Out[7]:
          a         b         c
0 -1.675422 -0.696623 -1.025674
1  0.032192  0.582190  0.214029
2 -0.134230  0.991172 -0.177654
3 -1.688784  1.275275  0.029581
4 -0.528649  0.858710 -0.244512

In [9]:
df['new_col'] = pd.Series([[1,2,3],[3,4,5],[5,6,7]])
df

Out[9]:
          a         b         c    new_col
0 -1.675422 -0.696623 -1.025674  [1, 2, 3]
1  0.032192  0.582190  0.214029  [3, 4, 5]
2 -0.134230  0.991172 -0.177654  [5, 6, 7]
3 -1.688784  1.275275  0.029581        NaN
4 -0.528649  0.858710 -0.244512        NaN
like image 150
EdChum Avatar answered Sep 17 '22 20:09

EdChum


What about

df = pd.DataFrame({0: [[1,2,3],[3,4,5],[5,6,7]]})
like image 39
Julien Spronck Avatar answered Sep 19 '22 20:09

Julien Spronck