有条件地替换pandas多索引数据帧中的数据

时间:2015-09-24 20:31:40

标签: python pandas python-3.4

在pandas多索引数据框中,如何在依赖于不同列中包含的特定条件的列中设置值?

所以,我的数据框基本上是这样的:

           COL1      COL2      COL3      COL4
foo 1 -1.322275  1.107506  1.253344 -0.331782
    2 -0.378448 -1.174557 -0.772984  1.476661
    3  0.046396  0.904299  0.768654 -0.168910
    4  1.396580  1.250713  0.193130 -0.454971
bar 1 -1.453794 -0.393206 -0.922908  0.762605
    2  1.375954 -1.304682  0.329339  0.606340
    3 -2.911151  0.011083  0.771964  1.620039
    4  0.040204  0.887082 -0.893575  1.129227

您可以使用以下代码创建:

arrays = [np.array(['foo','foo','foo','foo','bar','bar','bar','bar']),
          np.array([1,2,3,4,1,2,3,4])]
df = pd.DataFrame(np.random.randn(8,4), index=arrays)
df.columns = ['COL1','COL2','COL3','COL4']

我想评估'COL1',子帧'foo'表示大于0的值,并用新值COL1 / 1替换(就地不复制)相应行的'COL4'值。然后我想对子帧'bar'再做同样的事情,但是要评估'COL2'值。

我的实际数据帧非常庞大,所以我一直在努力找到一个比在行上更好的解决方案。我已经能够有条件地替换常规数据帧,但是,当我尝试更高级的多索引和设置时,某些东西没有点击。我可能会让事情变得更复杂,但距离充电墙约45分钟。

1 个答案:

答案 0 :(得分:0)

我没有完全明白你的目标替代你的目标'专栏,所以我做了一些通用的东西。您可以根据需要替换位。

以下是定义:

def repfunc(row,evalcol,replacecol):
    if row[evalcol] > 0:
        row[replacecol] = 999 #replace value goes here!
    return row

def repframe(df,repindex,evalcol,replacecol):
    df.sort_index(inplace=True)
    df.loc[repindex][replacecol] = df.loc[repindex].apply(lambda x: repfunc(x,evalcol,replacecol), axis=1).loc[:,replacecol]

以下是您的称呼方式:

repframe(df,'foo','COL1','COL4')

您可以根据需要替换参数以在数据框的另一个切片/列中重复操作。上面的操作更改了这样的数据框:

           COL1      COL2      COL3      COL4
foo 1  1.436672  0.213772 -0.705179 -1.297816
    2 -0.995535 -0.067389  0.290504 -0.794496
    3  1.375566  0.271896 -0.577298 -1.450002
    4 -0.603792 -0.450790 -1.484757  1.401513
bar 1  0.975558 -0.645254 -0.760839 -0.629055
    2 -1.972025 -0.108141  1.317623  0.126768
    3  1.947666  1.270041 -0.034555 -1.540862
    4 -3.124269  0.176528  1.815705  0.299059

进入这个:

           COL1      COL2      COL3        COL4
bar 1  0.975558 -0.645254 -0.760839   -0.629055
    2 -1.972025 -0.108141  1.317623    0.126768
    3  1.947666  1.270041 -0.034555   -1.540862
    4 -3.124269  0.176528  1.815705    0.299059
foo 1  1.436672  0.213772 -0.705179  999.000000
    2 -0.995535 -0.067389  0.290504   -0.794496
    3  1.375566  0.271896 -0.577298  999.000000
    4 -0.603792 -0.450790 -1.484757    1.401513

我认为您在使用多索引重置数据帧列时遇到问题,因为需要对多索引进行排序以便返回数据帧的视图(而不是副本)。据我所知,这是necessary if you want to perform this kind of replacement in multiindexed dataframes。请注意repframe使用sort_index调用inplace=True

我的版本总是将正值替换为999.它确实适用于'在这些行上,但如果没有它,我无法理解你是怎么做到的。