Mattpats
Mattpats

Reputation: 534

Return corresponding value in a dataframe

I have the following dataframe:

     price     sales
0  9611.89  0.013477
1  9611.88  0.032521
2  9611.87  0.047571
3  9611.86  0.107571
4  9611.81  0.257285

for i in df['price']:
    if i < 9611.87:
        print(i)
        break

The above loop returns the correct price. Now, I want it to print the corresponding value of i in the sales column, 0.107571

The below code does not work

for (i, ii) in df:
    if i < 9611.87:
        print(ii)
        break

Upvotes: 0

Views: 645

Answers (2)

DavidN
DavidN

Reputation: 712

You can accomplish this without looping. Pandas indexing is made exactly for this. You can read more about boolean masking (conditional filtering) here, and other indexing methods here.

Given the condition of 'price'<9611.87...

The following will return all columns and the rows of the dataframe with that condition:

df[df['price']<9611.87]

This will return a series of just the 'sales' column with the rows satisfying that condition:

df['sales'][df['price']<9611.87]

Lastly, since it looks like you only wanted the first item based on your loop, you can use .iloc to get a particular index of the returned series. In this case index 0:

df['sales'][df['price']<9611.87].iloc[0]

Upvotes: 1

chumbaloo
chumbaloo

Reputation: 721

Did you want to print all the values that are less than 9611.87? Have you considered filtering, like the following:

new_df = df[df['price']<9611.87]
print(new_df)
print(new_df['sales'])

Which should give the following output:

     price     sales
3  9611.86  0.107571
4  9611.81  0.257285
3    0.107571
4    0.257285
Name: sales, dtype: float64

Upvotes: 0

Related Questions