Why in Pandas DataFrame with mix elements types & size, when I change an element I get “ValueError”?

So Imagine that I have a dataframe as bellow (import pandas as pd, import numpy as np):

df = pd.DataFrame({'a':[np.array([1,2,3]), np.array([4,5,6]), np.array([7,8,9]), np.array([10,11,12]), np.array([13,14,15])],'b':[5,5,12,123,5]})

Now If I want to replace the third element in column ‘a’ using:

df.loc[2,'a']= np.array([53,23,4])

 I get the following error:

Traceback(most recent call last):File"...", line 3326,in run\_code exec(code\_obj, self.user\_global\_ns, self.user\_ns)File"\<ipython-input-67-4741bddaf261\>", line 1,in\<module\> df.loc[0,'a']= np.array([53,23,4])File"...", line 205,in \_\_setitem\_\_ self.\_setitem\_with\_indexer(indexer, value)File"...", line 547,in \_setitem\_with\_indexer "Must have equal len keys and value "ValueError:Must have equal len keys and value when setting with an iterable  

 Now If I remove the second column (‘b’) and make my dataframe as

df = pd.DataFrame({'a':[np.array([1,2,3]), np.array([4,5,6]), np.array([7,8,9]), np.array([10,11,12]), np.array([13,14,15])]})

and use exactly previous command to replace the 3rd item, I will not receive any error. What am I doing wrong here? What is the better practice to not have this error?

P.S. I am using Python 3.7.5 on ubuntu 18.10 and Pycharm IDE (2019.3.3). The version of my pandas is 0.25.3, numpy is 1.17.3 .

P.S.S. I know that indexing like

df['a'][2] = np.array([53,23,4])

works but still gives me a ‘SettingWithCopyWarning’ which also implies that this might not be a good practice.

The first thing you should understand is that SettingWithCopyWarning is a warning, and not an error. The real problem behind the warning is that it is generally difficult to predict whether a view or a copy is returned. In most cases, the warning was raised because you have chained two indexing operations together. The SettingWithCopyWarning was created to flag “chained assignment” operations. This is made easier to spot because you might be used (square brackets) twice, but the same would be true if you used other access methods such as .loc , .iloc and so on.

Moreover, you can change the behaviour of SettingWithCopyWarning warning using pd.options.mode.chained_assignment with three option “None/raise”/“warn”.