jam
jam

Reputation: 567

Create new pandas column with same list as every row?

I would like to create a new column in a dataframe that has a list at every row. I'm looking for something that will accomplish the following:

df = pd.DataFrame(data={'A': [1, 2, 3], 'B': ['x', 'y', 'z']})
list_=[1,2,3]
df['new_col] = list_
   A       B     new_col
0  1       x     [1,2,3]
1  2       y     [1,2,3] 
2  3       z     [1,2,3]

Does anyone know how to accomplish this? Thank you!

Upvotes: 1

Views: 1511

Answers (3)

harpan
harpan

Reputation: 8631

df = pd.DataFrame(data={'A': [1, 2, 3], 'B': ['x', 'y', 'z']})
list_=[1,2,3]
df['new_col'] = [list_]*len(df)

Output:

    A   B   new_col
0   1   x   [1, 2, 3]
1   2   y   [1, 2, 3]
2   3   z   [1, 2, 3]

Tip: list as a variable name is not advised. list is a built in type like str, int etc.

Upvotes: 2

mathisfun
mathisfun

Reputation: 261

df['new_col'] = [[1,2,3] for j in range(df.shape[0])]

Upvotes: 1

Silenced Temporarily
Silenced Temporarily

Reputation: 1004

df['new_col'] = pd.Series([mylist for x in range(len(df.index))])

("list" is a terrible variable name, so I'm using "mylist" in this example).

Upvotes: 1

Related Questions