返回值大于但说明了参数

时间:2019-12-10 05:31:48

标签: python pandas

我想返回所有大于特定整数的值。但是,我有一个单独的列来确定应大于的值。使用下面的df,如果DirectionRight,则应返回X大于mainX的所有行。如果DirectionLeft,则应返回小于X的所有行。

df = pd.DataFrame({
        'Time' : ['09:00:00.1','09:00:00.1','09:00:00.1','09:00:00.1','09:00:00.1','09:00:00.1','09:00:00.2','09:00:00.2','09:00:00.2','09:00:00.2','09:00:00.2','09:00:00.2'],
        'Group' : ['I','J','I','J','I','J','I','J','I','J','I','J'],                  
        'Label' : ['A','B','C','D','E','F','A','B','C','D','E','F'],                 
        'X' : [8,4,3,8,7,4,7,3,3,4,6,1],
        'Y' : [3,6,4,8,5,2,8,8,2,4,5,1],
        'mainX' : [5,5,5,5,5,5,5,5,5,5,5,5],
        'mainY' : [5,5,5,5,5,5,5,5,5,5,5,5],
        'Direction' : ['Left','Right','Left','Right','Left','Right','Left','Right','Left','Right','Left','Right']
    })

def greater(df):

    for val in df['Direction']:

        if val == 'Right':
            Forward = df[df['X'] > df['mainX']]

        elif val == 'Left':
            Forward = df[df['X'] < df['mainX']]

        else:
            continue

        return Forward

df1 = greater(df)

出局:

          Time Group Label  X  Y  mainX  mainY Direction
1   09:00:00.1     J     B  4  6      5      5     Right
2   09:00:00.1     I     C  3  4      5      5      Left
5   09:00:00.1     J     F  4  2      5      5     Right
7   09:00:00.2     J     B  3  8      5      5     Right
8   09:00:00.2     I     C  3  2      5      5      Left
9   09:00:00.2     J     D  4  4      5      5     Right
11  09:00:00.2     J     F  1  1      5      5     Right

预期:

          Time Group Label  X  Y  mainX  mainY Direction
1   09:00:00.1     I     C  3  4      5      5      Left
2   09:00:00.1     J     D  8  8      5      5     Right
3   09:00:00.2     I     C  3  2      5      5      Left

2 个答案:

答案 0 :(得分:2)

设置您的条件并使用loc

cond1 = (df["Direction"].eq("Right"))&(df["X"]>df["mainX"])
cond2 = (df["Direction"].eq("Left"))&(df["X"]<df["mainX"])

print (df.loc[cond1|cond2])

#
         Time Group Label  X  Y  mainX  mainY Direction
2  09:00:00.1     I     C  3  4      5      5      Left
3  09:00:00.1     J     D  8  8      5      5     Right
8  09:00:00.2     I     C  3  2      5      5      Left

答案 1 :(得分:1)

只需像其他答案一样使用布尔型掩码,或者将query与pythonic条件一起使用

df.query("(Direction == 'Right' and X > mainX) or (Direction == 'Left' and X < mainX)")

将输出


         Time Group Label  X  Y  mainX  mainY Direction
2  09:00:00.1     I     C  3  4      5      5      Left
3  09:00:00.1     J     D  8  8      5      5     Right
8  09:00:00.2     I     C  3  2      5      5      Left