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