基于间隔索引,熊猫的数据帧执行查找?

我正在尝试构建一个简单的系统,系统要求用户输入年龄,输入保额(或他/她想要收到的金额),然后根据这些输入,系统将告诉用户他要支付的溢价(或金额)。


到目前为止,我已经能够让代码工作(在某种程度上),但是我的问题是现在迭代所有列。


代码如下:


import pandas as pd

#data = pd.read_csv("/Users/Noel/Desktop/Transition.csv")



data = {'5000': ['18.67','19.79','22.16','26.38','29.17'],

        '7500': ['20.07','21.28','23.82','28.36','31.99'],

        '10000': ['21.46', '22.76', '25.48', '30.33', '34.81']}


transition_table = pd.DataFrame(data, index=['18-25','26-30','31-35','36-40','41-45'])


print('Hello, welcome to Axe!')

age = int(input('Please enter the age of the Policyholder: '))

sum_assured = int(input('Please enter the Sum assured of the Policyholder: '))


if age >= 18 and age <= 25 and sum_assured == 5000:

        row0 = transition_table.iloc[0, 0]

        print(row0)


elif age >= 26 and age <=30 and sum_assured == 5000:

        col0 = transition_table.iloc[1, 0]

        print(col0)


print('A Policyholder of age ' + age + ' with a sum assured of ' + sum_assured + ' will pay a premium of ' )

因此,当我输入年龄为18岁,保额为5000时,我应收到以下结果:18岁的保单持有人的保额为5000,将支付18.7的保费


如果我输入的年龄为27岁,保额为10000,我希望收到以下结果:27岁的保单持有人的保额为10000,将支付22.76的保费


我想我应该使用for循环来进行迭代,但我遇到了困难。


天涯尽头无女友
浏览 74回答 1
1回答

小怪兽爱吃肉

使用numpy方法解决了这个问题。此方法将值(或值)映射到条柱中,例如,年龄 27 将映射到第二个间隔(索引 1),代码为:digitizearrayimport pandas as pdimport numpy as npdata = {'5000': ['18.67','19.79','22.16','26.38','29.17'],&nbsp; &nbsp; &nbsp; &nbsp; '7500': ['20.07','21.28','23.82','28.36','31.99'],&nbsp; &nbsp; &nbsp; &nbsp; '10000': ['21.46', '22.76', '25.48', '30.33', '34.81']}index = np.array([25, 30, 35, 40, 45])transition_table = pd.DataFrame(data, index=index)def get_value(age, sum_assured):&nbsp; row = np.digitize(age, transition_table.index, right=True)&nbsp; col = str(sum_assured)&nbsp; return transition_table.iloc[row, :][col]用法:age = int(input("Enter age"))sum_assured = input("Enter Sum Assured")get_value(age, sum_assured)结果:>>Enter age 27>>Enter Sum Assured 10000>>'22.76'希望这有帮助,如果有什么不清楚的地方,请写一条评论。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python