繁体   English   中英

Python中的索引匹配

[英]index match in Python

我有以下数据框

价值 一个
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

我正在尝试做的事情:

例子:

我正在考虑某种 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.

我尝试为此使用 numpy 并对其进行索引... np.where 看起来很有希望,但我一直卡在第二部分。 任何人都可以帮忙吗? 可以安全地假设这些值按升序排序。

我很抱歉这么说,但你的问题根本不清楚。 你犯了奇怪的错误,没有清楚地解释你想要什么。

那么,这个程序做了什么:

  1. 如果 A < B,则从同一行返回“值”;
  2. 如果 A > B,则从当前 B 到末尾查看整个数据帧,并从 B 大于 A 的第一行获取“值”。

如果不是您想要的,请给出更清楚的解释)很高兴为您提供帮助。

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])

编辑:输出为 1.0、3.0、4.0。 我刚刚看到你注意到了你的迹象,对不起)

暂无
暂无

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

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