2

I'm working with this dataframe:

       P       Q        date
0  [2, 3, 4]  [2, 2]   2019-3-18
1      [fff]     [2]   2019-3-18
2         []     [2]  2019-10-24
3     [4, 5]     [2]    2019-1-1

I can easily transform any list, no matter how many elements in it. For example:

df.loc[1,'Q']=[5,6]

df:

          P       Q        date
0  [2, 3, 4]  [2, 2]   2019-3-18
1      [fff]  [5, 6]   2019-3-18
2         []     [2]  2019-10-24
3     [4, 5]     [2]    2019-1-1

However, if I change 'date' column type to datetime, the code doesn't work anymore:

df["date"] = pd.to_datetime(df["date"])
df.loc[2,'Q']=[5,6]

File "...", line 18, in <module>
 df.loc[2,'Q']=[5,6]
File "C:\Users\usuario\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\core\indexing.py", line 671, in __setitem__
self._setitem_with_indexer(indexer, value)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\core\indexing.py", line 1018, in _setitem_with_indexer
raise ValueError(
 File "C:\Users\usuario\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\core\indexing.py", line 1018, in _setitem_with_indexer
raise ValueError(
ValueError: Must have equal len keys and value when setting with an iterable

Any idea on how I could avoid that error? I would really appreciate it.

EDIT: I just found that using .at instead of .loc the code works perfectly. It let you even replace a list for any kind of data, and not only another list. Found it here: Python pandas insert list into a cell

  • 1
    I'm not thrilled with my answer because it is just a workaround and doesn't answer the question of why this is happening. Through playing around, I found out that this occurs whenever they is a column with a dtype other than object. – Polkaguy6000 Feb 27 '21 at 16:24

1 Answers1

1

Here is a workaround, but it's far from perfect and doesn't actually address why this is happening.

To get around the issue, add [:] to df.loc[2,'Q']. It should look like this:

df.loc[2,'Q'][:] = [5,6]

The reason this works is because you are specifying that you want to change the entire list within loc[2,'Q'].

Polkaguy6000
  • 1,150
  • 1
  • 8
  • 15
  • 2
    I found more information on the thing that was bugginge. The reason for the error is because the assignment is ambiguous https://stackoverflow.com/questions/23227171/assignment-to-containers-in-pandas – Polkaguy6000 Feb 27 '21 at 16:42