在熊猫数据框中查找任意两列的总和是否超过X

时间:2018-11-16 03:53:58

标签: python pandas

Sample。列是属性,行是观察。

我想提取任何两个属性之和超过指定值(例如0.7)的行。然后,在两个新列中,列出对总和的贡献越来越大的列标题。

我是python的新手,因此在生成数据框后我一直无法继续工作。

1 个答案:

答案 0 :(得分:1)

您可以这样做:

import pandas as pd
from itertools import combinations

THRESHOLD = 8.0

def valuation_formula(row):
    l = [sorted(x) for x in combinations(row, r=2) if sum(x) > THRESHOLD]
    if(len(l) == 0):
        row["smaller"], row["larger"] = None, None
    else:
        row["smaller"], row["larger"] = l[0]  # since not specified by OP, we take the first such pair
    return row  

contribution_df = df.apply(lambda row: valuation_formula(row), axis=1)

那么,如果

df = pd.DataFrame({"a" : [1.0, 2.0, 4.0], "b" : [5.0, 6.0, 7.0]})
     a    b
0  1.0  5.0
1  2.0  6.0
2  4.0  7.0

然后,contribution_df

     a    b  smaller  larger
0  1.0  5.0      NaN     NaN
1  2.0  6.0      NaN     NaN
2  4.0  7.0      4.0     7.0

HTH。