Python 函数不根据数据框中的数字返回匹配行

我在 pandas 中有一个像这样格式化的数据框。


(df)

School ID      Column 1       Column 2     Column 3

School 1                      8100         8200  

School 2       9-999 

School 3                      9300         9500 

School 4                      7700         7800 

School 5       8999

....

我希望能够输入一个值,例如如果该值是直接命中第1列(字符串类型),例如输入数字:9-999,它将返回


Input Number: 9-999


School ID     Column 1

School 2      9-999

但如果输入的数字介于第 2 列和第 3 列(浮点数)中的数字之间,我想返回关联的学校 ID,如下所示。


Input Number: 8110


School ID      Column 2    Column 3

School 5       8100        8200

现在我有这个代码:


def find(num) :

d1=df.loc[df['Column 1']==num]

if len(d1)>0 :

    return d1[['School ID','Column 1']]

else :

    return df.loc[(num>= df['Column 2']) & (num<= df['Column 3'])][['School ID','Column 2','Column 3']]

但我收到一条错误消息:“返回”外部函数


犯罪嫌疑人X
浏览 51回答 1
1回答

摇曳的蔷薇

s = '9-999'q = df[df['Column_1']==str(s)]if len(q):&nbsp; &nbsp; print(q)else:&nbsp; &nbsp; m = df[['Column_2', 'Column_3']].apply(lambda x: x['Column_2'] <= s <= x['Column_3'], axis=1)&nbsp; &nbsp; print(df[m])印刷:&nbsp; School_ID Column_1&nbsp; Column_2&nbsp; Column_31&nbsp; School 2&nbsp; &nbsp; 9-999&nbsp; &nbsp; &nbsp; &nbsp;0.0&nbsp; &nbsp; &nbsp; &nbsp;0.0为了s = 8110:&nbsp; School_ID Column_1&nbsp; Column_2&nbsp; Column_30&nbsp; School 1&nbsp; &nbsp; &nbsp; &nbsp; 0&nbsp; &nbsp; 8100.0&nbsp; &nbsp; 8200.0编辑:为了获得一致的数据类型,您可以将 Column2 和 Column3 转换为浮点数:s = '8110'q = df[df['Column_1']==str(s)]df['Column_2'] = df['Column_2'].astype(float)df['Column_3'] = df['Column_3'].astype(float)if len(q):&nbsp; &nbsp; print(q)else:&nbsp; &nbsp; s = float(s)&nbsp; &nbsp; m = df[['Column_2', 'Column_3']].apply(lambda x: x['Column_2'] <= s <= x['Column_3'], axis=1)&nbsp; &nbsp; print(df[m])
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python