[問題] 有關df.loc[]的問題

作者: sssh (叫我松高魂 ~~)   2018-12-04 20:39:05
範例如下
https://imgur.com/vaZab8V
如果我今天要找出Store 1中的Cost
df.loc["Store 1"]["Cost"]
老師說用這種方法好像會出現問題因此不建議
原文如下:
This looks pretty reasonable and gets us the result we wanted. But chaining
can come with some costs and is best avoided if you can use another approach.
In particular, chaining tends to cause Pandas to return a copy of the
DataFrame instead of a view on the DataFrame. For selecting a data, this is
not a big deal, though it might be slower than necessary. If you are changing
data though, this is an important distinction and can be a source of error.
想請教大家,老師在這邊講的具體上來說是什麼問題?
小的有點看不懂這樣的方法會帶來什麼狀況@@
不知道是否有前輩可以幫忙指點一二?
作者: gmccntzx1 (o.O)   2018-12-04 21:25:00
參考: https://stackoverflow.com/questions/23296282還有這個: https://bit.ly/2Edy74i簡單來說, `df.loc["Store 1"]["Cost"]` 會透過 2 次__getitem__ 來取值,後面行為的開始執行時取決於前面行為的完成時機。若資料可以允許寫成 `df.loc[:, ('Store 1', 'cost')]`則 pandas 可以一次根據後面的參數取值,相對來說較快關於回傳值是 view 還是 copy ,基本上可以照著stackoverflow 那篇回答的規則去判斷。要了解的更詳細的話,推薦你直接去追 source code:pd.DataFrame.__getitem__ : https://git.io/fpPuH裡面有寫到好幾種狀況,比較值得注意的地方有self._slice (generic._slice): https://git.io/fpPzxself._take (generic._take): https://git.io/fpP2E修正一下:上面的 generic 應該是 generic.NDFrame所以說,用 chain indexing 問題在於一般情況下不容易判斷出取的值到底是 view 還是 copy (不了解如stackoverflow 那篇回答所說的規則),而非資料在記憶體中的情況差異所影響。而因為會影響取值結果是 view/copy 的情況很多種,所以官方還是建議少用 chain indexing。
作者: TitanEric (泰坦)   2018-12-05 10:12:00
推優文
作者: sssh (叫我松高魂 ~~)   2018-12-05 10:32:00
感謝gmccntzxl的分享
作者: Angesi (小雲豹)   2018-12-06 17:05:00
df.loc["Store 1","Cost"] 指定位置讀 應該最簡單用chain index 實在有點奇怪或者 隱含索引 df.iloc[0, 0] 也行

Links booklink

Contact Us: admin [ a t ] ucptt.com