pandas select rows by condition code example

Example 1: fetch row where column is equal to a value pandas

df.loc[df['column_name'] == 'value']

Example 2: only keep rows of a dataframe based on a column value

df.loc[df['column_name'] == some_value]

Example 3: or condition in pandas

df1 = df[(df.a != -1) & (df.b != -1)]

Example 4: new dataframe based on certain row conditions

filterinfDataframe = dfObj[(dfObj['Sale'] > 30) & (dfObj['Sale'] < 33) ]

Example 5: slice dataframe pandas based on condition

# To slice pandas dataframe by condition

frioMurteira = data.loc[(data["POM"] == "Murteira") & (data["TMP"] > 7.2), ["DTM","TMP"]]

Example 6: pandas select rows by multiple conditions

>>> df["A"][(df["B"] > 50) & (df["C"] == 900)]
2    5
3    8
Name: A, dtype: int64
    
>>> df.loc[(df["B"] > 50) & (df["C"] == 900), "A"]
2    5
3    8
Name: A, dtype: int64
>>> df.loc[(df["B"] > 50) & (df["C"] == 900), "A"].values
array([5, 8], dtype=int64)
>>> df.loc[(df["B"] > 50) & (df["C"] == 900), "A"] *= 1000
>>> df
      A   B    C
0     9  40  300
1     9  70  700
2  5000  70  900
3  8000  80  900
4     7  50  900