0

I have the following df:

A   B   C
1  NaN NaN 
2  NaN NaN
3  NaN NaN
4  NaN NaN

I want this:

A   B         C
1  'Blue'   'Purple'
2  'Yellow' 'Yellow'   
3  'Green'  'Orange'  
4  'Blue'   'Brown'

What I have tried to do:

df1.B = ['Blue', 'Yellow', 'Green', 'Blue']
df1.C = ['Purple', 'Yellow', 'Orange', 'Brown']

But i get the following error:
ValueError: Length of values does not match length of index

But there are the same number of colors in the list as in the df.

Please help.

user8322222
  • 489
  • 3
  • 14
  • 28

3 Answers3

0

A column in a dataframe is a Series object so you want

 df['B'] = pd.Series( ['Blue', 'Yellow', 'Green', 'Blue'])
vencaslac
  • 2,727
  • 1
  • 18
  • 29
0

U can try use:

df1 = df1.assign(B=pd.Series(['Blue', 'Yellow', 'Green', 'Blue']).values)

And there is more information about on this post: Adding new column to existing DataFrame in Python pandas

Lucas Araújo
  • 429
  • 5
  • 17
0

Well if the length of the list that you want to assign to column B and C are equal to number of rows in dataframe then you can directly assign the list as below :

df['B'] = ['Blue', 'Yellow', 'Green', 'Blue']
Genesis
  • 50
  • 4