Reputation: 67
I want to generate a list of ranges based on lists to subset rows from a dataframe.
import numpy as np
import pandas as pd
start_index = [10,20,30]
end_index = [15,25,35]
range_list = [10:15, 20:25, 30:35]
# assume df is a dataframe with 50 rows
df = df.loc[np.r_range_list,:]
How to generate the range_list from start_index and end_index? Any suggestions is welcome!
Upvotes: 1
Views: 487
Reputation: 863226
Use zip
with list
for list of tuples:
range_list = list(zip(start_index, end_index))
print (range_list)
[(10, 15), (20, 25), (30, 35)]
And then use list comprehension for filter:
dfs = [df.loc[s:e] for s, e in range_list]
If want one big DataFrame add concat
:
dfbig = pd.concat(dfs)
Al together, convert zip
object to list is not necessary:
dfbig = pd.concat([df.loc[s:e] for s, e in zip(start_index, end_index)])
Upvotes: 9