Vivek Anand
Vivek Anand

Reputation: 391

how to insert column data as a list of list in pandas

I have a list of list like

a = [[1,2],[2,3]]

my dataframe is like this:

        name 
0       John
1       Mike

i want to insert this list of lists to a new column called 'Score' like this:

        name    Score
0       John    [[1,2],[2,3]]
1       Mike    [[1,2],[2,3]]

I tried doing this:

df['Score'] = 0
df['Score'] = df['Score'].astype(object)

Now setting directly

df['Score'] = a

gives error.Then i tried using

df.at[1,'Score'] = a

This works but for only row =1 but i want to set all the rows of that column = a.So i tried .loc

df.loc[:,'Score'] = a

but it didnt help.

Upvotes: 0

Views: 96

Answers (1)

Reza
Reza

Reputation: 2025

Try this

a = [[1,2],[2,3]]
df = pd.DataFrame({'name': ['John', 'Mike']})

df['score'] = [a for _ in range(df.shape[0])]

Output:

   name             score
0  John  [[1, 2], [2, 3]]
1  Mike  [[1, 2], [2, 3]]

Upvotes: 1

Related Questions