【问题标题】:filter pandas dataframe based in another column根据另一列过滤熊猫数据框
【发布时间】:2014-12-27 07:26:55
【问题描述】:

这可能是一个基本问题,但我无法找到解决方案。我有两个数据框,具有相同的行和列,称为 Volumes 和 Price,它们是这样的

音量

Index    ProductA    ProductB     ProductC     ProductD    Limit
0          100          300          400           78       100
1          110          370           20           30       100
2           90          320          200          121       100
3          150          320          410           99       100
....

价格

Index    ProductA    ProductB     ProductC     ProductD    Limit
0           50          110          30           90        0
1           51          110          29           99        0
2           49          120          25           88        0
3           51          110          22           96        0
....

我想将 0 分配给价格数据框的“单元格”,它对应的交易量小于限制列上的数量

所以,理想的输出应该是

价格

Index    ProductA    ProductB     ProductC     ProductD    Limit
0           50          110          30            0         0
1           51          110           0            0         0
2            0          120          25           88         0
3           51          110          22            0         0
....

我试过了

import pandas as pd
import numpy as np
d_price = {'ProductA' : [50, 51, 49, 51], 'ProductB' : [110,110,120,110], 
'ProductC' : [30,29,25,22],'ProductD' : [90,99,88,96], 'Limit': [0]*4}
d_volume = {'ProductA' : [100,110,90,150], 'ProductB' : [300,370,320,320], 
'ProductC' : [400,20,200,410],'ProductD' : [78,30,121,99], 'Limit': [100]*4}
Prices = pd.DataFrame(d_price)
Volumes = pd.DataFrame(d_volume)

Prices[Volumes > Volumes.Limit]=0

但我没有对价格数据框进行任何更改...显然我很难理解布尔切片,任何帮助都会很棒

【问题讨论】:

    标签: python pandas boolean slice


    【解决方案1】:

    问题出在

    Prices[Volumes > Volumes.Limit]=0
    

    由于每行的限制不同,您应该使用,例如,应用如下:

    Prices[Volumes.apply(lambda x : x>x.Limit, axis=1)]=0
    

    【讨论】:

      【解决方案2】:

      你可以使用面具来解决这个问题,我也不是专家,但这个解决方案可以满足你的需求。

      test=(Volumes.ix[:,'ProductA':'ProductD'] >= Volumes.Limit.values)
      final = Prices[test].fillna(0)
      

      【讨论】:

        猜你喜欢
        • 2021-12-01
        • 1970-01-01
        • 2020-05-05
        • 2020-08-08
        • 2019-12-09
        • 1970-01-01
        • 2020-08-16
        • 2016-08-31
        • 2021-08-19
        相关资源
        最近更新 更多