Skip to content Skip to sidebar Skip to footer

Extract Rows Range With .between(), And Specific Columns, From Pandas DataFrame?

I just got tripped on this: consider this example: >>> import pandas as pd >>> df = pd.DataFrame({ 'key':[1,3,6,10,15,21], 'columnA':[10,20,30,40,50,60], 'c

Solution 1:

You can just use the standard way of slicing DataFrames:

df[df['key'].between(2,16)][['key','columnA','columnC']]

Solution 2:

Well, turns out, I need to use .loc:

>>> df.loc[df['key'].between(2, 16), ["columnA"]]
   columnA
1       20
2       30
3       40
4       50

... or rather, as I originally wanted it (and also adding the "key" column):

>>> df.loc[df['key'].between(2, 16), ["key", "columnA", "columnC"]]
   key  columnA  columnC
1    3       20      202
2    6       30      330
3   10       40      404
4   15       50      550

Post a Comment for "Extract Rows Range With .between(), And Specific Columns, From Pandas DataFrame?"