简体   繁体   中英

Selecting rows with specific values in pandas

I have the following dataframe in pandas:

print(df)

  id  num1   num2   num3  num4  num5  num6  
  a   43      25    37     8    36    20  
  b   43      36    19     25   44    15  
  c   43      25    23     38   1     8  

How do I select all the rows that have the values 8 and 25 in them and create a new dataframe for just those rows?.The dataframe has thousands of rows and the values could be in any column.

You can create a boolean check for each of the values in each row and then slice the dataframe. Here is an example that requires the row to have BOTH 8 and 25. If you want any row that has 8 or 25, use | instead of &

ix = df.eq(8).any(axis=1) & df.eq(25).any(axis=1)
df2 = df[ix]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM