簡體   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