2013-12-10 112 views
1

我想根据我的熊猫数据框中的第一个索引值进行条件替换。如果我有一个数据帧,例如:替换熊猫多索引数据帧中的列值

from pandas import * 
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], 
      ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']] 

tuples = zip(*arrays) 

index = MultiIndex.from_tuples(tuples, names=['first','second']) 
data = DataFrame(randn(8,2),index=index,columns=['c1','c2']) 

我想我应该能够通过列替换值:

data.ix['bar']['c1'] = -999 

但这返回原始数据框中,持平。任何人都可以解释这应该怎么做,为什么我目前的方法不起作用?

+2

您可能更喜欢使用NaN来查找缺失的数据。 –

+0

@AndyHayden - 真的够了,我可能会用NaN。我只是在这里选择了-999这个例子。 – tnknepp

回答

1

您使用了错误的符号。尝试

data.ix['bar','c1'] = -999 

索引的第一个元素指向行,第二个元素指向列。请参阅Docs

+0

谢谢。我喜欢.ix,因为它比.loc更普遍。再次感谢 – tnknepp

1

也许这:

data.c1[ 'bar' ] = -999 

data[ 'c1' ][ 'bar' ] = -999 

猜测的是,在这里data.ix['bar']['c1']返回一个副本,而不是进行查看。看到this

+0

有趣,感谢您的参考。我从来不知道这一点。 – tnknepp

3

你可以使用.loc

>>> data.loc["bar", "c1"] 
second 
one  0.369406 
two  0.691445 
Name: c1, dtype: float64 
>>> data.loc["bar", "c1"] = -999 
>>> data 
         c1  c2 
first second      
bar one -999.000000 0.302155 
     two -999.000000 -1.260789 
baz one  0.103455 -0.556967 
     two  -1.600112 0.491787 
foo one  0.779901 -0.885565 
     two  -1.041722 -0.570302 
qux one  -1.152093 -1.767028 
     two  -0.364624 -0.302240 

[8 rows x 2 columns]