Lanie909
Lanie909

Reputation: 919

Search For Value in Panda/Print Out Adjacent Row

I need to find all rows in column "A" that equal 0, then print out the adjacent values in column "B". Any help on how to do this in pandas would be greatly appreciated.

Upvotes: 1

Views: 2278

Answers (2)

jpp
jpp

Reputation: 164773

This is one way:

import pandas as pd

df = pd.DataFrame([[0, 5], [1, 10], [2, 6], [3, 2],
                   [4, 9], [5, 1], [0, 3], [1, 3]], columns=['A', 'B'])

df.loc[[False] + list(df.set_index('A').index.get_loc(0))[:-1], 'B']

# 1    10
# 7     3
# Name: B, dtype: int64

Upvotes: 0

Yilun Zhang
Yilun Zhang

Reputation: 9018

Assume your dataframe is called df. To get all rows in column "A" that equal to 0:

df_a = df[df["A"] == 0]

Then, to get index of those rows:

df_a_index = df_a.index

Then, you want the next row of these indices:

df_b_index = df_a_index + 1

Then,

df.iloc[df_b_index]["B"]

will give you the adjacent (next) row in column "B".

Upvotes: 2

Related Questions