首页 > 解决方案 > 如何从最近的列中获取值?

问题描述

训练数据集

df_table = pd.DataFrame()
df_table["A"] = [0.2, 0.2, 0.2, 0.2, 0.2,
                 0.4, 0.4, 0.4, 0.4, 0.4,
                 0.6, 0.6, 0.6, 0.6, 0.6,
                 1.5, 1.5, 1.5, 1.5, 1.5,
                 2.5, 2.5, 2.5, 2.5, 2.5,
                 3.0, 3.0, 3.0, 3.0, 3.0]

df_table[450] = [1, 5, 20, 30, 40,
                 1, 5, 8, 10, 20,
                 1, 5, 10, 15, 25,
                 2, 7, 15, 20, 30,
                 2, 7, 15, 20, 35,
                 2, 8, 20, 30, 40]

df_table[500] = [3, 15, 25, 60, 80,
                 4, 10, 15, 20, 30,
                 5, 10, 15, 30, 40,
                 5, 10, 20, 30, 45,
                 7, 10, 20, 35, 50,
                 8, 15, 25, 60, 80]

如果 的输入值为A = 0.2,并且temperature = 476,我想从最接近 的列中获取值476,在这种情况下,来自500which 的值将是3

同样,如何从450和中获取两个值500。对于这种情况13. 所以这将是最近的较小列和最近的较高列的值。

标签: pythonpandasdataframemapping

解决方案


您需要根据可用列和您的值计算要使用的正确列。

然后本地化您的数据框的第一个值,其中A填充您的搜索值并查询您刚刚计算的列:

import pandas as pd

df_table = pd.DataFrame()
df_table["A"] = [0.2, 0.2, 0.2, 0.2, 0.2, 0.4, 0.4, 0.4, 0.4, 0.4,
                 0.6, 0.6, 0.6, 0.6, 0.6, 1.5, 1.5, 1.5, 1.5, 1.5,
                 2.5, 2.5, 2.5, 2.5, 2.5, 3.0, 3.0, 3.0, 3.0, 3.0]

df_table[450] = [1, 5, 20, 30, 40, 1, 5, 8, 10, 20,
                  1, 5, 10, 15, 25, 2, 7, 15, 20, 30,
                  2, 7, 15, 20, 35, 2, 8, 20, 30, 40]

df_table[500] = [3, 15, 25, 60, 80, 4, 10, 15, 20, 30,
                  5, 10, 15, 30, 40, 5, 10, 20, 30, 45,
                  7, 10, 20, 35, 50, 8, 15, 25, 60, 80]

# integer columns harvested from the dataframe
T_values = [n for n in df_table.columns if isinstance(n,int)]

# what I want to query
myA = 0.2
myT = 476

# get the column names that are near myT
minColNear_myT = max(a for a in T_values if a <= myT)
maxColNear_myT = min(a for a in T_values if a >= myT)

# localize the first one where myA matches    
first_one_matching_myA = df_table.loc[(df_table['A'] == myA).idxmax()]

# output the values of the columns near myT
print(minColNear_myT, myT, first_one_matching_myA[minColNear_myT])
print(maxColNear_myT, myT, first_one_matching_myA[maxColNear_myT])

输出:

450 476 1.0
500 476 3.0

要仅输出与myT存在的两列相比更接近的列,并使用差异最小的列:

closest = sorted( (k for k in T_values), key = lambda x:abs(x - myT) )[0]
print(closest,  myT, first_one_matching_myA[closest])

推荐阅读