作者sssh (叫我松高魂 ~~)
看板Python
标题[问题] 有关df.loc[]的问题
时间Tue Dec 4 20:39:05 2018
范例如下
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.
想请教大家,老师在这边讲的具体上来说是什麽问题?
小的有点看不懂这样的方法会带来什麽状况@@
不知道是否有前辈可以帮忙指点一二?
--
◤ ◤ ◣
● Ο ο ◤ ◣ ◣
◣ ◤ 。 ο ○ 。 ○ °●
◣ ≡ ◤ ° ο Ο ◣ ◤
◤ ◣ ≡ ◤
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 1.163.71.122
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1543927149.A.227.html
3F:→ gmccntzx1: 简单来说, `df.loc["Store 1"]["Cost"]` 会透过 2 次 12/04 21:26
4F:→ gmccntzx1: __getitem__ 来取值,後面行为的开始执行时取决於前面 12/04 21:28
5F:→ gmccntzx1: 行为的完成时机。 12/04 21:28
6F:→ gmccntzx1: 若资料可以允许写成 `df.loc[:, ('Store 1', 'cost')]` 12/04 21:30
7F:→ gmccntzx1: 则 pandas 可以一次根据後面的参数取值,相对来说较快 12/04 21:31
感谢gmccntzxl前辈的分享,
我刚刚研究了一下,我的理解大致上是这样:
chain indexing容易出现问题的状况是在赋值时,
两个中括号放在一起时,
第一个中括号的工作(取值)
但是取值後返回的不一定是view或是copy(依照内存状况不一定)
所以当在处理第二的中括号(赋值)时,
若第一个返回的是copy就有可能会产生SettingWithCopy
这也是为什麽chain indexing这麽不稳定的原因
不知道我这样的理解是否正确?
※ 编辑: sssh (1.163.71.122), 12/04/2018 23:49:08
8F:推 gmccntzx1: 关於回传值是 view 还是 copy ,基本上可以照着 12/05 00:48
9F:→ gmccntzx1: stackoverflow 那篇回答的规则去判断。 12/05 00:49
10F:→ gmccntzx1: 要了解的更详细的话,推荐你直接去追 source code: 12/05 00:51
12F:→ gmccntzx1: 里面有写到好几种状况,比较值得注意的地方有 12/05 00:53
15F:→ gmccntzx1: 修正一下:上面的 generic 应该是 generic.NDFrame 12/05 01:01
16F:→ gmccntzx1: 所以说,用 chain indexing 问题在於一般情况下不容易 12/05 01:03
17F:→ gmccntzx1: 判断出取的值到底是 view 还是 copy (不了解如 12/05 01:04
18F:→ gmccntzx1: stackoverflow 那篇回答所说的规则),而非资料在记忆 12/05 01:06
19F:→ gmccntzx1: 体中的情况差异所影响。 12/05 01:07
20F:→ gmccntzx1: 而因为会影响取值结果是 view/copy 的情况很多种,所以 12/05 01:11
21F:→ gmccntzx1: 官方还是建议少用 chain indexing。 12/05 01:14
22F:推 TitanEric: 推优文 12/05 10:12
23F:→ sssh: 感谢gmccntzxl的分享 12/05 10:32
24F:推 Angesi: df.loc["Store 1","Cost"] 指定位置读 应该最简单 12/06 17:05
25F:→ Angesi: 用chain index 实在有点奇怪 12/06 17:05
26F:→ Angesi: 或者 隐含索引 df.iloc[0, 0] 也行 12/06 17:19