簡體   English   中英

基於另一列過濾熊貓數據框

[英]filter pandas dataframe based in another column

這可能是一個基本問題,但是我無法找到解決方案。 我有兩個數據框,具有相同的行和列,稱為“數量”和“價格”,如下所示

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

但我沒有對“價格”數據框進行任何更改...顯然,我在理解布爾切片時遇到了困難,任何幫助都將非常有用

問題出在

Prices[Volumes > Volumes.Limit]=0

由於限制在每一行上都不同,因此您應該使用例如以下所示的方法:

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

您可以使用遮罩來解決此問題,我也不是專家,但是此解決方案可以完成您想做的事情。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM