This is a followup to
extract column value based on another column pandas dataframe
I have more than one row that matches the column value and want to know how to iterate to efficiently retrieve each value when there are multiple matches.
Dataframe is
JavaScript
x
11
11
1
A B
2
p1 1
3
p1 2
4
p3 3
5
p2 4
6
p4 3
7
p5 5
8
p6 2
9
p7 5
10
around 10000 rows
11
The below will always pick p3
JavaScript
1
2
1
df.loc[df['B'] == 3, 'A'].iloc[0]
2
So I tried to iterate like
JavaScript
1
4
1
if(len(df.loc[df['B'] == 3, 'A'])) > 1:
2
for i in range(0,len(df.loc[df['B'] == 3, 'A']))-1):
3
print(i,df.loc[df['B'] == 3, 'A'].iloc[i])))
4
And it prints
JavaScript
1
3
1
0 p3
2
1 p4
3
for all matching values
However is there a more efficient way to do this?
Advertisement
Answer
You can get all matching values by without using .iloc[0]
in the df.loc
code, as follows:
JavaScript
1
2
1
df.loc[df['B'] == 3, 'A']
2
Output:
JavaScript
1
4
1
2 p3
2
4 p4
3
Name: A, dtype: object
4
The 2
4
on the left of the output are the original row indices. You can use this information if want to know from which rows are these 2 extracted data originated from.