Skip to content Skip to sidebar Skip to footer

Selecting Rows And Columns In Pandas Dataframe

pandas dataframe has , number of items selling quantity FRUIT YESTERDAY TODAY TOMORROW Apple 5 5 3 Apple 3 5 3 Orange 6

Solution 1:

Try using pd.DataFrame.query after masking where dataframe equals to zero:

df.mask(df == 0).query('YESTERDAY == TOMORROW')

Output:

    FRUIT  YESTERDAY  TODAY  TOMORROW
1   Apple        3.0    5.0       3.0
4  Grapes        7.0    7.0       7.0
6   Mango        2.0    8.0       2.0

And,

df.mask(df == 0).query('YESTERDAY == TODAY')

Output:

    FRUIT  YESTERDAY  TODAY  TOMORROW
0   Apple        5.0    5.0       3.0
4  Grapes        7.0    7.0       7.0
7   Mango        4.0    4.0       6.0

Solution 2:

Create a boolean mask to filter your dataframe:

cols = ['YESTERDAY', 'TODAY', 'TOMORROW']
mask = df[cols].ne(0).all(1) & df[cols].std(axis=1).ne(0)
out = df[mask]

Mask detail:

  • df[cols].ne(0).all(1) keep rows which have no 0 in their columns.
  • df[cols].std(axis=1).ne(0) keep rows which have at least one different value in their columns . A standard deviation of 0 means all values are equals (7, 7, 7).

First output:

>>> out.loc[out['YESTERDAY'] == out['TODAY']]
   FRUIT  YESTERDAY  TODAY  TOMORROW
0  Apple          5537  Mango          446

Second output:

>>> out.loc[out['YESTERDAY'] == out['TOMORROW']]
   FRUIT  YESTERDAY  TODAY  TOMORROW
1  Apple          3536  Mango          282

Post a Comment for "Selecting Rows And Columns In Pandas Dataframe"