首页 > 解决方案 > 从依赖于其他数据的数据中获取价值

问题描述

我正在尝试获取介于 0,1 之间的 l 输入。l 输入将用于 A 列。第二个输入将是“mesafe”列,因此结果必须为 23,即 A 和 mesafe 的零列。我得到一些错误。

import pandas as pd
import numpy as np

def var():
    df = pd.read_csv('l_y.txt')
    l=float(input("speed of the wind:"))
    w=int(input("range:"))
    for l in range(0, 1) and w in range(0, 100) :
        print(df['A'].values[0])




l_y.txt=(  mesafe      A     B     C     D     E     F
       0     100     23    18    14     8     4     0
       1    1000    210   170   110    60    40    30
       2    5000    820   510   380   300   230   160
       3   10000   1600  1200   820   560   400   250
       4   20000   2800  2100  1600  1000   820   500
       5   50000   5900  4600  3400  3200  1600  1100
       6  100000  10000  8100  6100  3900  2800  2000 )    






Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    var()
  File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\ml.py", line 
8, in var
    for l in range(0, 1) and w in range(0, 100) :
TypeError: 'bool' object is not iterable

标签: pythonpandas

解决方案


好的,我假设您想从矩阵中获取某个值,具体取决于两个输入值 l 和 w,因此如果 l 介于 0 和 1 之间,则应选择列“A”。(我进一步假设,如果 l 在 1 nd 2 之间,它是列 'B',2 <= l < 3 -> 'c',依此类推......)该行直接从 w 派生,数据位于mesafe-column:如果 w 在 0 和 100 之间 -> 第 0 行,在 100 和 1000 之间 -> 第 1 行,依此类推...

好吧,这可以通过以下方式实现:

l = .3   # let's say user types 0.3

l 和字母之间有一些映射:

l_mapping = [1, 5, 12, 20, 35, 50]    # These are the thresholds between the columns A...F

l_index = np.searchsorted(l_mapping, l)   # calculate the index of the column letter

col = df.columns[1:][l_index]    # this translates l to the column names from A...F

col     # look what col is when l was < 1
Out: 'A'

w = 42   # now the user Input for w is 42

row = np.searchsorted(df.mesafe.values, w)   # this calculates the fractional index of w in df.mesafe

row
Out: 0

因此,使用这两个公式,您可以获得列和行信息来索引您想要的结果:

df[col].iloc[row]
Out: 23

在一个函数中总结这一切看起来像这样:

def get_l_y(l, w, df_ly):
    l_mapping = [1, 5, 12, 20, 35, 50]
    l_index = np.searchsorted(l_mapping, l)
    col = df_ly.columns[1:][l_index]
    row = np.searchsorted(df.mesafe.values, w)
    print(l, w, col, row)    # print Input and calculated row- and column- values for testing purpose, can be deleted/commented out if everything works as you want 
    return df[col].iloc[row]

此函数需要 l、w 和矩阵的 pandas-dataframe 作为输入参数并返回 l_y。


推荐阅读