代码之家  ›  专栏  ›  技术社区  ›  Lisa

如何使用Python找到一个表中哪些标记行位于或高于另一个表的某些点?

  •  2
  • Lisa  · 技术社区  · 1 年前

    我是Python的新手,正在努力理解如何对这种特定情况进行编码。我附上了一张Excel屏幕截图,以更好地描述我正在使用的表格和图形。从表1中,列标题10-13用作x值。行#标签提供1-6之间的哪一行受到影响。表2提供了2个点:A和B。我们如何确定1-6行中的哪一行与A点相交或在A点之上?B点呢?

    从逻辑上讲,我知道点A应该在所有6行或以下,而B应该在第4行和第6行或下方。当被问及A时,Python应该打印{1、2、3、4、5、6},当被问及B时,Python应打印{4,6}。

    然而,我们如何将这个过程转换为在Python中完成,因为Python中有两个像这样设置的表?

    Table 1 and Table 2

    我尝试过这样的方法,但它不起作用,我认为它只会输出点A的总行数,如6,点B的总行数为2,而不是我正在寻找的特定Row#Label。

    # Iterate through the points in Table #1
    for i in range(len(table_one)):
        x = table_one[i][0]
        y = table_one[i][1]
    
    # Iterate through the matrices in Table #2
    for j in range(len(table_two)):
        m = table_two[j]
    # Calculate the x and y values of the matrix
        m_x = np.sum(m, axis=0) * [i]
        m_y = np.sum(m, axis=1) * [i]
    
    # Compare the x and y values of the point with those of the matrix
    if np.any((np.abs(x - m_x) <= 0.5) & (np.abs(y - m_y) <= 0.5)):
    
    # Increment the counter variable
        intersection_count = intersection_count + 1
    
    1 回复  |  直到 1 年前
        1
  •  2
  •   Sheldon    1 年前

    在Python中处理表时,我建议您使用 pandas 。它通常是这样导入的 import pandas as pd .

    让我们考虑以下示例表:

    data1= {'11': [0.2, 0.3, 0.1, 2, 0.6, 1.2], '12': [0.3, 0.33, 0.18, 2.5, 1, 1.4]}
    data2= {'Point': ["A","B"], 'X': [11,12], 'Y': [0.18, 1.24]}
    table1 = pd.DataFrame(data=data1)
    table2 = pd.DataFrame(data=data2)
    

    表1类似于快照中左侧的表,表2是右侧的表。 如果我正确理解你的问题,对于表1中给定的横坐标(X),你想检查哪些样本在表2中的纵坐标(Y)之上。

    让我们考虑一下:

    abscissa = 11
    

    那么您的阈值是:

    threshold = table2[table2.X==abscissa]['Y'].to_numpy()
    

    第一个表中对应的列名为 X = str(abscissa) .

    要检查相应panda系列中的哪些值大于或等于阈值,可以执行以下操作:

    table1[X].ge(threshold[0])
    

    当然,这会为所有行返回“True”。 如果使用重复相同的操作 abscissa = 12 ,这将返回:

    0    False
    1    False
    2    False
    3     True
    4    False
    5     True
    Name: 12, dtype: bool