返回大于但考虑参数的值

2024-04-29 14:32:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我想返回所有大于特定整数的值。但是,我有一个单独的列来确定应该大于多少。使用下面的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

Tags: rightdataframedftimegroup整数valleft
2条回答

就像另一个答案一样使用布尔掩码,或者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

设置条件并使用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

相关问题 更多 >