【问题标题】:Replace column values in pandas multiindexed dataframe替换熊猫多索引数据框中的列值
【发布时间】:2013-12-28 14:38:19
【问题描述】:

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

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

但这会返回原始数据帧,保持不变。谁能解释这应该怎么做以及为什么我目前的方法不起作用?

【问题讨论】:

  • 您可能更喜欢使用 NaN 来处理缺失数据。
  • @AndyHayden - 确实如此,我可能会使用 NaN。我只是在这里选择了-999作为示例。

标签: python-2.7 pandas multi-index


【解决方案1】:

也许是这样的:

data.c1[ 'bar' ] = -999

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

我的猜测是这里data.ix['bar']['c1'] 正在返回一个副本而不是视图。见this

【讨论】:

  • 有趣,感谢您的参考。我从来不知道。
【解决方案2】:

你可以使用.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]

【讨论】:

    【解决方案3】:

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

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

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

    【讨论】:

    • 谢谢。我喜欢 .ix,因为它比 .loc 更通用。再次感谢
    猜你喜欢
    • 2017-07-23
    • 2016-07-06
    • 1970-01-01
    • 2022-06-24
    • 2019-05-21
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多