根据另一列筛选pandas数据帧

2024-05-21 07:33:34 发布

您现在位置:Python中文网/ 问答频道 /正文

这可能是一个基本问题,但我还没有找到解决办法。我有两个数据帧,具有相同的行和列,称为卷和价格,如下所示

数量

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
....

价格

^{pr2}$

我想将0分配给Prices数据帧的“单元格”,它对应的容量小于Limit列上的容量

所以,理想的输出是

价格

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

但是我没有得到价格数据框的任何变化。。。显然,我很难理解布尔切片,任何帮助都会很好


Tags: 数据importindexas价格pricepdprices
2条回答

你可以用面具来解决这个问题,我也不是一个专家,但这个解决方案做你想做的。在

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

问题出在

Prices[Volumes > Volumes.Limit]=0

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

^{pr2}$

相关问题 更多 >