python - 如何从最近的列中获取值?
问题描述
训练数据集
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
,在这种情况下,来自500
which 的值将是3
。
同样,如何从450
和中获取两个值500
。对于这种情况1
和3
. 所以这将是最近的较小列和最近的较高列的值。
解决方案
您需要根据可用列和您的值计算要使用的正确列。
然后本地化您的数据框的第一个值,其中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])
推荐阅读
- angular - 设置 Mat-Select 的默认值不起作用
- jenkins - launcher.gcr.io/google/jenkins2 不绘制图表
- python-attrs - 如何指定不是类属性的 __init__ 参数
- visual-studio-code - SourceMaps的VSCode Gatsy调试错误
- c# - 表达式树中的访问方法组
- spring - 使用 Spring 处理 Hibernate 乐观锁定
- jquery - 如何从 Header 中检索表单数据信息
- java - OpenStreetMap 标签 - 配置
- android - 我的应用程序在启动时崩溃
- java - 线程“main”java.lang.Error 中的异常:未解决的编译错误:PrintStream i 类型中的方法 printf(String, Object[])