Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas.DataFrame select by interval of indexes

Tags:

python

pandas

I would like to know, in a pythonic way, how could I select elements in the Pandas.Dataframe inside a given interval in their indexes. Basically I wish to know if there is a command like pandas.Series.between for DataFrame.index .

example:

df1 = pd.DataFrame(x, index=(1,2,...,100000000), columns=['A','B','C'])

df2 = df1.between(start=10, stop=100000)

I think it is curious not easily finding anything related to this.

like image 765
phasselmann Avatar asked Mar 18 '23 05:03

phasselmann


1 Answers

You can just use the subscript notation with loc which is label based indexing:

In [3]:

df2 = df1.loc[10:100000]
df2
Out[3]:
         A    B    C
10     NaN  NaN  NaN
11     NaN  NaN  NaN
12     NaN  NaN  NaN
13     NaN  NaN  NaN
14     NaN  NaN  NaN
15     NaN  NaN  NaN
.....
99994  NaN  NaN  NaN
99995  NaN  NaN  NaN
99996  NaN  NaN  NaN
99997  NaN  NaN  NaN
99998  NaN  NaN  NaN
99999  NaN  NaN  NaN
10000  NaN  NaN  NaN

[99991 rows x 3 columns]

You also mention not being able to find documentation about this but it's pretty easy to find and clear: http://pandas.pydata.org/pandas-docs/stable/indexing.html

like image 115
EdChum Avatar answered Mar 19 '23 18:03

EdChum