首页 > 解决方案 > 两个熊猫数据框的值之间的 if 语句

问题描述

我想用两个熊猫数据框的值创建一个 if 语句(我要比较的值在第 0 列):

编辑:

首先,我想检查 df1 的值大于 df2 的值的次数。

for row in df1:
    if df1[0] > df2[0]:
       Print('Ok')
    else:
       Print('not OK')

我得到的是:

ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

编辑第 2 号:

由于我没有时间尝试您的所有建议,并且由于我需要一个快速解决方案,因此我得到了以下结果:

excessLoadB1l=[]

indexYB1=loadC1C2B1.index.tolist()

tempLB1=energyBalanceB1['sumSupply_B1'].tolist()

for item in tempLB1:

    if item < 0:

        item=item

    else:

        item=0

    excessLoadB1l.append(item)

excessLoadB1=pd.DataFrame({'excessLoadB1':excessLoadB1l}).set_index([indexYB1])

我用正负值创建了一个列表

tempLB1=energyBalanceB1['sumSupply_B1'].tolist()

我想将其分成两个不同的 DataFrame。我借用了索引

indexYB1=loadC1C2B1.index.tolist()

对于正值:

excessSupplyB1l=[]

indexZB1=loadC1C2B1.index.tolist()

tempSB1=energyBalanceB1['sumSupply_B1'].tolist()

for item in tempSB1:

    if item > 0:

        item=item

    else:

        item=0

    excessSupplyB1l.append(item)


excessSupplyB1=pd.DataFrame({'excessSupplyB1':excessSupplyB1l}).set_index([indexZB1])

标签: pythonpandasdataframefor-loopif-statement

解决方案


稍微快一点

for i, j in enumerate(df.itertuples()):
    if j[0] > df1[0].iloc[i]:
        print("OK")
    else:
        print("Not OK")

推荐阅读