2

I cannot seem to reassign a value in a pandas dataframe with a list. Python wants to iterate over the list and I didn't think it would do that. For example, if I have the following:

import pandas as pd
val1 = [0, 1, 2]
val2 = [3, 4, 5]
d_list = []
for v1, v2 in zip(val1, val2):
    d_list.append({'val1':v1, 'val2':v2})
df = pd.DataFrame(d_list)
val3 = [6, 7, 8, 9]
df['val3'] = [val3]*len(df)
print df

I get my expected output:

   val1  val2          val3
0     0     3  [6, 7, 8, 9]
1     1     4  [6, 7, 8, 9]
2     2     5  [6, 7, 8, 9]

Now I want to reassign the values in val3:

df.loc[0, 'val3'] = [11, 12, 13, 14]

and I get the following error:

raise ValueError('Must have equal len keys and value '
ValueError: Must have equal len keys and value when setting with an iterable

What am I doing wrong here?

Scott Boston
  • 147,308
  • 15
  • 139
  • 187
John
  • 377
  • 3
  • 10

1 Answers1

4

What you are looking for is df.at

Try:

df.at[0, 'val3'] = [11, 12, 13, 14] 

From the docs:

Similar to loc, in that both provide label-based lookups. Use at if you only need to get or set a single value in a DataFrame or Series

http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.at.html

David Sidarous
  • 1,202
  • 1
  • 10
  • 25