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.
Asked
Active
Viewed 2,104 times
1
-
Can you add sample data, expected output and what you try? – jezrael Feb 13 '18 at 14:18
-
1Possible duplicate of [Select rows from a DataFrame based on values in a column in pandas](https://stackoverflow.com/questions/17071871/select-rows-from-a-dataframe-based-on-values-in-a-column-in-pandas) – Georgy Feb 13 '18 at 14:26
2 Answers
2
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".

TYZ
- 8,466
- 5
- 29
- 60
-
Note this method assumes your index is of form `list(range(n))`. You may have to apply `.reset_index()` first. – jpp Feb 13 '18 at 14:46
0
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

jpp
- 159,742
- 34
- 281
- 339