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?

1
  • 4
    try df.at[0, 'val3'] = [11, 12, 13, 14] Commented May 13, 2019 at 15:43

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.