Insert list of lists into single column of pandas df

前端 未结 2 1880
天涯浪人
天涯浪人 2021-01-17 19:04

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

相关标签:
2条回答
  • 2021-01-17 19:29

    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
    
    0 讨论(0)
  • 2021-01-17 19:31

    What about

    df = pd.DataFrame({0: [[1,2,3],[3,4,5],[5,6,7]]})
    
    0 讨论(0)
提交回复
热议问题