add new columns and fill with string in python

Viewed 243

I want to add a new column and fill with strings respectively to the number of rows I have.

I did

df['new column'] = ['open', closed']

but it did not match the number of indexes I have. What should I add to my script so the desired strings will appear respectively follows the number of rows in the data frame.

Thank you.

1 Answers

If want solution working for pair or unpair length of rows you can use map by dictionary from list and enumerate:

df = pd.DataFrame({'a':range(5)})

L = ['open', 'closed']

df['new column'] =  (df.index % len(L)).map(dict(enumerate(L)))
print (df)
   a new column
0  0       open
1  1     closed
2  2       open
3  3     closed
4  4       open
Related