Python dataframe repeat column data in each cell as a list

I am trying to repeat the whole data in a column in each each cell of the column. My code:

df3=pd.DataFrame({
    'x':[1,2,3,4,5],
    'y':[10,20,30,20,10],
    'z':[5,4,3,2,1]
})

df3 = 
   x   y  z
0  1  10  5
1  2  20  4
2  3  30  3
3  4  20  2
4  5  10  1

df3['z'] = df['z'].agg(lambda x: list(x))

Present output:

KeyError: 'z'

Expected output:

df= 

   x   y                z
0  1  10  [5, 4, 3, 2, 1]
1  2  20  [5, 4, 3, 2, 1]
2  3  30  [5, 4, 3, 2, 1]
3  4  20  [5, 4, 3, 2, 1]
4  5  10  [5, 4, 3, 2, 1]

2 answers

  • answered 2020-08-11 00:47 BEN_YO

    Check with

    df3['new_z']=[df3.z.tolist()]*len(df3)
    

    More safe

    df3['new_z']=[df3.z.tolist() for x  in df.index]
    

  • answered 2020-08-11 01:10 wwnde

    Another way is to list(df.column.values)

     df3.assign(z=[list(df3.z.values)]*len(df3))
    
    
     x   y                z
    0  5  10  [5, 4, 3, 2, 1]
    1  4  20  [5, 4, 3, 2, 1]
    2  3  30  [5, 4, 3, 2, 1]
    3  2  20  [5, 4, 3, 2, 1]
    4  1  10  [5, 4, 3, 2, 1]