Destination .loc [:, ['A', 'B']] allows you to change the dtype of columns?

I was confused because I could not immediately change the two columns using .loc[:,['A', 'B'] , which I think because it returns a copy instead of a view. I cannot find in Indexing and Data Selection the final guide on when it will return the view and when it will return the copy.

I use pandas 0.18, I see that in the old version of the documentation (pandas 0.13) she said: "Whenever an array of labels or a Boolean vector is involved in the indexing operation, the result will be a copy", but I can not find it in the current documentation

 pd.__version__ # u'0.18.0' df = pd.DataFrame({'A': ['1', '2', '3', '4', '5', '6', '7', '8'], 'B': ['1', '2', '3', '4', '5', '6', '7', '8'], 'C': ['1', '2', '3', '4', '5', '6', '7', '8']}) df.dtypes #A object #B object #C object #dtype: object df2 = df.copy() df2[['A', 'B']] = df2.loc[:,['A' , 'B']].astype(float) # Works df2.dtypes #A float64 #B float64 #C object #dtype: object df2 = df.copy() df2.loc[:,['A', 'B']] = df2.loc[:,['A' , 'B']].astype(float) # Does NOT work df2.dtypes #A object #B object #C object #dtype: object 

None of them raise a SettingWithCopy warning. So I'm a little confused about why the purpose of df2.loc[:, ['A', 'B']] has no effect.

On closer inspection, I see that this is not a copy , since in another test I assigned a dataframe with different values ​​and I was β€œsaved” in df2 , but dtypes df2 cannot be β€œset” through the destination .loc[:, ['A', 'B']] .

Is there a reason why the assignment .loc[:, ['A', 'B']] = does not change dtypes and [['A', 'B']] = does?

+5
source share
1 answer

In fact, there was only issue and a note to the document was added about this. Basically, .loc tries to drop the original dtype on assignment, where [] not. This is expected behavior, but a little subtle.

+4
source

All Articles