根据条件计算最小值

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

将一列添加到数据框中,其中每个项目的最小值仅来自字典对应的列。如何在计算最小值时添加条件 - 如果所选列中的值大于“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
2个回答
0
投票

按照您

apply
的方法,它需要布尔索引with
gt
):

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]

0
投票

收据会相当简单:

  1. 根据字典 my_dict 中的
    Col0
    检索每行的相关列。
  2. 过滤这些列以仅保留那些大于
    Col7
    中的值的值。
  3. 最后计算这些过滤值的
    min

代码中的表达可能如下所示:

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]
})

# Adding the 'min' column by applying 
# a function across each row
df['min'] = df.apply(lambda row: min([row[col] for col in my_dict.get(row['Col0'], []) if col in row and row[col] > row['Col7']]), axis=1)

print(df)
© www.soinside.com 2019 - 2024. All rights reserved.