Kyle
Kyle

Reputation: 387

Pandas DataFrame Create a Column that holds a list

I would like to take a list and create a new column in a pandas dataframe. Here is the code which I have created, notice it will throw an error.

d={'range':list(range(0,100))}
print(d)
df=pd.DataFrame(d)

l=['var1','var2','var3']
print(df)
df['var_list']=l

The correct result would be a dataframe with 2 columns, the first being range, the second being a list of variables "var_list" which has a static value over all the rows.

Here is an example of the desired output: enter image description here

In fact, it does not have to be a list if that is not possible to perform in a dataframe, it can be the values from the list in a string separated by a space or some delimiter.

Upvotes: 2

Views: 6022

Answers (1)

BENY
BENY

Reputation: 323226

This is a little bit tricky

df['var_list'] = [l] * len(df)
df.head(4)
Out[333]: 
    range            var_list
0       0  [var1, var2, var3]
1       1  [var1, var2, var3]
2       2  [var1, var2, var3]
3       3  [var1, var2, var3]

Upvotes: 4

Related Questions