Pandas 数据帧索引异常?

Pandas dataframe indexing anomaly?

下面的 Python 代码首先创建一个多索引 pandas 数据框,然后尝试更改其中一个元素。有问题的元素在更改前后打印以验证更改是否有效。问题是它不起作用。请查看这段代码,让我知道问题出在哪里。

import numpy as np
import pandas as pd
arrays = [['Apple','Apple','Banana','Banana','Cherry','Cherry'],
         ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
df = pd.DataFrame(np.zeros([3, 6]), index=['A', 'B', 'C'], columns=index)
df.insert(0, 'Insert', [1,2,3]) # the absence of this line makes the problem disappear
print df['Apple']['one']['A'] # this line correctly prints 0
df['Apple']['one']['A'] = 15
print df['Apple']['one']['A'] # this line again prints 0 when we should get 15 now

您需要执行以下操作:

df.loc['A', ('Apple', 'one')] = 15

这不是异常,您正在做的 'chained assignment' 基本上只更改了基础数据的副本。有人将能够更准确地告诉您发生了什么,但要正确索引,请使用 .loc 或 .ix。

看到这个答案:

How to deal with SettingWithCopyWarning in Pandas?