2

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.

1
  • Can you show an example of your input and output Commented Nov 12, 2017 at 21:11

1 Answer 1

4

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]
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks much Wen, I figured it would be something really simple.
@Kyle Yw, basically, the back end mechanism, is the list of list each sub list will be recognized as a cell value :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.