Home > Net >  Is there a better way to select rows from a pandas DataFrame based on multiple conditions?
Is there a better way to select rows from a pandas DataFrame based on multiple conditions?

Time:12-24

I'm trying to select rows from a pandas DataFrame based on multiple conditions. The code looks like this:

row = videos_train_df[
             (videos_train_df['pid1']==pid1)
            &(videos_train_df['pid2']==pid2)
            &(videos_train_df['vid'] ==vid)]

Is there any better way (in terms of code readability) to do the same thing?

CodePudding user response:

You can use query

row = videos_train_df.query(
    f"pid1 == {pid1} and pid2 == {pid2} and vid == {vid}"
)

See also this question.

CodePudding user response:

I will do all after eq

new = df[df[['pid1','pid2','vid']].eq([pid1,pid2,vid]).all(1)]
  • Related