Skip to content
Advertisement

Iterate over column values matched value based on another column pandas dataframe

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

A  B
p1 1
p1 2
p3 3
p2 4
p4 3
p5 5
p6 2
p7 5
... around 10000 rows

The below will always pick p3

df.loc[df['B'] == 3, 'A'].iloc[0]

So I tried to iterate like

 if(len(df.loc[df['B'] == 3, 'A'])) > 1:
                        for i in range(0,len(df.loc[df['B'] == 3, 'A']))-1):
                            print(i,df.loc[df['B'] == 3, 'A'].iloc[i])))

And it prints

0 p3
1 p4

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:

df.loc[df['B'] == 3, 'A']

Output:

2    p3
4    p4
Name: A, dtype: object

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement