Home > OS >  How to get data through pandas with conditions
How to get data through pandas with conditions

Time:06-07

How can i get the symbols of retdf

import pandas as pd
returns = [0.0322, 0.3211, 0.0032, 0.00349]
symbols = ['A', 'B', 'C', 'D']

retdf = pd.DataFrame(returns, index=symbols, columns=['ret'])
retdf = retdf.ret.nlargest(3).values > 0.03
print(retdf)

The above code outputs

array([ True,  True, False])

CodePudding user response:

You need to use boolean indexing after your condition is met.

tmp = retdf.ret.nlargest(3)
(tmp.loc[tmp > 0.03]).index
> Index(['B', 'A'], dtype='object')

CodePudding user response:

Try:

>>> retdf[retdf['ret'] > 0.03].nlargest(3, 'ret')
      ret
B  0.3211
A  0.0322

# OR

>>> retdf.nlargest(3, 'ret').query('ret > 0.03')
      ret
B  0.3211
A  0.0322
  • Related