Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

I have a Python pandas DataFrame rpt:

Rpt

<class 'pandas.core.frame.DataFrame'>

MultiIndex: 47518 entries, ('000002', '20120331') to ('603366', '20091231')

Data columns:

STK_ID       47518 non-null  values

STK_Name     47518 non-null  values

RPT_Date     47518 non-null  values

sales        47518 non-null  values

I can filter the rows whose stock id is '600809' like this:

rpt[rpt['STK_ID'] == '600809']

<class 'pandas.core.frame.DataFrame'>

MultiIndex: 25 entries, ('600809', '20120331') to ('600809', '20060331')

Data columns:

STK_ID       25 non-null   values

STK_Name     25 non-null   values

RPT_Date     25 non-null   values

Sales       25 non-null    values

and I want to get all the rows of some stocks together, such as ['600809','600141','600329']. That means I want a syntax like this:

stk_list = ['600809','600141','600329']

rst = rpt[rpt['STK_ID'] in stk_list]

# this does not works in pandas

Since pandas do not accept the above command, how to achieve the target?

1 Answer

0 votes
by (106k points)

To filter dataframe rows if the value in the column is in a setlist of values you can use the isin method which is shown how to do in the below-mentioned piece of code:-

rpt[rpt['STK_ID'].isin(stk_list)].

Another thing you can use is ranges by using below is the code for the same:-

b = df[(df['a'] > 1) & (df['a'] < 5)]

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...