简体   繁体   中英

index match in Python

I have the following dataframe

value A B
1.0 7.0 8.0
2.0 9.0 8.8
3.0 9.5 9.1
4.0 10.0 9.4
5.0 13.0 8.4
6.0 15.0 8.5

What I'm attempting to do:

example:

I'm thinking some sort of if/else statetement:

    -if 
        A < B
    return 1.0 ==> since A=7.0 < B=8.0
    -else: 
        if A > B
         look at the closest values from B column that match the target value A.
         Let's say the value A=9.0 so in this example it's going to be 8.8 and 9.1. 
         I need to take the larger number out of these 2 and return the 
         corresponding value from value column. 
         So in this case it'd return 3.0.

I tried using numpy for this, and indexing it... np.where looked promising but I keep getting stuck in the second part. Can anyone help? It's safe to assume that the values are sorted in the ascending order.

I'm sorry to say it, but your question is not clear at all. You made strange mistakes and did not explain clearly what you wanted.

So, what this program does:

  1. If A < B, return "value" from the same line;
  2. If A > B, looks through the whole dataframe from the current B up to the end and takes "value" from the first line where B is more than A.

If it is not what you wanted, please, give more clear explanation) Delighted to help you.

import pandas as pd
df = pd.DataFrame({
               "value": [1., 2., 3., 4., 5., 6], 
               'A': [7., 9., 9.5, 10., 13., 15.],
               'B': [8., 8.8, 9.1, 9.4, 8.4, 8.5]
             })
for i in range(df.shape[0]):
    if df['A'][i] < df['B'][i]: 
        print(df["value"][i])
    else:
        for j in range(i, df.shape[0]):
            if df['A'][i] < df['B'][j]:
                print(df["value"][j])

Edited: output is 1.0, 3.0, 4.0. I've just seen that you noticed your signs, sorry)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM