有条件的最小值

问题描述 投票:0回答:1

将一列添加到数据框中,其中每个项目的最小值仅来自字典对应的列。如何在计算最小值时添加条件 - 如果所选列中的值大于“Col7”列中的值?

import pandas as pd
my_dict={'Item1':['Col1','Col3','Col6'],
'Item2':['Col2','Col4','Col6','Col8']
        }
df=pd.DataFrame({
            'Col0':['Item1','Item2'],
            'Col1':[20,25],
            'Col2':[89,15],
            'Col3':[36,30],
            'Col4':[40,108],
            'Col5':[55,2],
            'Col6':[35,38],
            'Col7':[30,20]
            })

df['min']=df.apply(lambda r:r[[col for col in my_dict.get(r['Col0'], []) if col in r]].min(),axis=1) 

结果应该是:

df=pd.DataFrame({
            'Col0':['Item1','Item2'],
            'Col1':[20,25],
            'Col2':[89,15],
            'Col3':[36,30],
            'Col4':[40,108],
            'Col5':[55,2],
            'Col6':[35,38],
            'Col7':[30,20],
            'min':[35,38]
            })
python pandas
1个回答
0
投票

按照您的方法

apply
,它需要布尔索引

df["min"]= (
    df.apply(lambda r: r.reindex(my_dict[r["Col0"]])
             .loc[lambda s: s.gt(r["Col7"])].min(), axis=1)
)

输出:

    Col0  Col1  Col2  Col3  Col4  Col5  Col6  Col7  min
0  Item1    20    89    36    40    55    35    30   35
1  Item2    25    15    30   108     2    38    20   38

[2 rows x 9 columns]
© www.soinside.com 2019 - 2024. All rights reserved.