Answers for "pandas filter by data range"

1

how to slice dataframe based on daterange in pandas

In [15]: df = pd.DataFrame([1, 2, 3], index=[dt.datetime(2013, 1, 1), dt.datetime(2013, 1, 3), dt.datetime(2013, 1, 5)])

In [16]: df
Out[16]: 
            0
2013-01-01  1
2013-01-03  2
2013-01-05  3

In [22]: start = df.index.searchsorted(dt.datetime(2013, 1, 2))

In [23]: end = df.index.searchsorted(dt.datetime(2013, 1, 4))

In [24]: df.iloc[start:end]
Out[24]: 
            0
2013-01-03  2
Posted by: Guest on June-18-2020
0

pandas filter on range of values

import pandas as pd

#initialize dataframe
df = pd.DataFrame({'a': [2, 4, 8, 5], 'b': [2, 0, 9, 7]})

#check if the values of df['a'] are in the range(3,6)
out = df['a'].isin(range(3,6))

#filter dataframe
filtered_df = df[out]

print('Original DataFramen-------------------n',df)
print('nFiltered DataFramen-------------------n',filtered_df)
Posted by: Guest on May-03-2021

Python Answers by Framework

Browse Popular Code Answers by Language