【问题标题】:Pandas: Why does order of selection matter?Pandas:为什么选择顺序很重要?
【发布时间】:2013-11-18 22:10:21
【问题描述】:

假设我有一个 pandas.DataFrame,比如说

In [1]: df = pd.DataFrame([['a', 'x'], ['b', 'y'], ['c', 'z']],  
                          index=[10, 20, 30],  
                          columns=['first', 'second'])

In [2]: df
Out[2]:
   first second
10     a      x
20     b      y
30     c      z

我想用第二列的相应条目更新第一列的前两个条目。首先我尝试了

to_change = df.index <= 20
df[to_change]['first'] = df[to_change]['second']

但这不起作用。然而,

df['first'][to_change] = df['second'][to_change]

工作正常。

谁能解释一下?这种行为背后的理性是什么?虽然我经常使用 pandas,但我发现这类问题有时让我很难预测一段特定的 pandas 代码实际上会做什么。也许有人可以提供一些见解,帮助我改进我对 pandas 内部运作的心理模型。

【问题讨论】:

标签: python pandas


【解决方案1】:

在 master/0.13 中(很快发布)

这将警告(可通过引发/忽略选项控制)您正在修改副本

In [1]: df = pd.DataFrame([['a', 'x'], ['b', 'y'], ['c', 'z']],  
   ...:                           index=[10, 20, 30],  
   ...:                           columns=['first', 'second'])

In [2]: df
Out[2]: 
   first second
10     a      x
20     b      y
30     c      z

In [3]: to_change = df.index <= 20

In [4]: df[to_change]['first'] = df[to_change]['second']
pandas/core/generic.py:1008: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
  warnings.warn(t,SettingWithCopyWarning)

In [5]: df['first'][to_change] = df['second'][to_change]

【讨论】:

  • 如果我第一次学习如何使用 pandas 时出现这个警告就好了!
猜你喜欢
  • 1970-01-01
  • 2013-05-18
  • 1970-01-01
  • 2015-12-01
  • 1970-01-01
  • 2014-01-06
  • 1970-01-01
  • 2018-02-01
  • 2017-06-27
相关资源
最近更新 更多