Reputation: 203
Let's say I have 2 DataFrames like this:
df1
Id B
3 alpha 1
18 alpha 3
125 alpha 5
230 alpha 9
where 3, 18, 125, 230
are the index of df1
and:
df2
Id B
1 Beta 21
2 Beta 33
5 Beta 120
7 Beta 36
10 Beta 32
14 Beta 71
15 Beta 210
21 Beta 53
123 Beta 22
127 Beta 1227
128 Beta 11
227 Beta 7
235 Beta 18
My question : How can I browse my df2 to extract the rows coming before and after each row of my df1 based on the index?
My desired output :
df2
Id B
2 Beta 33
5 Beta 120
15 Beta 210
21 Beta 53
123 Beta 22
127 Beta 1227
227 Beta 7
235 Beta 18
Upvotes: 2
Views: 40
Reputation: 3103
A more verbose way to accomplish this is get the location of the indexes from df1
and plus-minus one to them.
df = pd.concat([df1, df2]).sort_index()
li = []
for ind in df1.index:
ind_loc = df.index.get_loc(ind)
li.extend([ind_loc - 1, ind_loc + 1])
print(df.iloc[li])
Upvotes: 1
Reputation: 863226
Use searchsorted
for positions, add one previous values, join by numpy.r_
and select by iloc
:
a = df2.index.searchsorted(df1.index)
df = df2.iloc[sorted(np.r_[a, a-1])]
print (df)
Id B
2 Beta 33
5 Beta 120
15 Beta 210
21 Beta 53
123 Beta 22
127 Beta 1227
227 Beta 7
235 Beta 18
Upvotes: 3