简体   繁体   English

Python中的索引匹配

[英]index match in Python

I have the following dataframe我有以下数据框

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

What I'm attempting to do:我正在尝试做的事情:

example:例子:

I'm thinking some sort of if/else statetement:我正在考虑某种 if/else 语句:

    -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.我尝试为此使用 numpy 并对其进行索引... np.where 看起来很有希望,但我一直卡在第二部分。 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;如果 A < B,则从同一行返回“值”;
  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.如果 A > B,则从当前 B 到末尾查看整个数据帧,并从 B 大于 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.编辑:输出为 1.0、3.0、4.0。 I've just seen that you noticed your signs, sorry)我刚刚看到你注意到了你的迹象,对不起)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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