【问题标题】:Performing Lookup based on Interval indexing, Pandas's Dataframes?执行基于区间索引的查找,Pandas 的数据帧?
【发布时间】:2020-07-10 19:18:39
【问题描述】:

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

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

这是代码:

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 时,我应该会收到以下输出: 保额为 5000 的 18 岁保单持有人将支付 18.7 的保费

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

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

【问题讨论】:

    标签: python pandas loops dictionary


    【解决方案1】:

    使用 numpy digitize 方法解决了这个问题。此方法将一个值(或array 个值)映射到 bin 中,例如 age 27 将映射到第二个区间(索引 1),代码:

    import pandas as pd
    import numpy as np
    
    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']}
    
    index = np.array([25, 30, 35, 40, 45])
    transition_table = pd.DataFrame(data, index=index)
    
    def get_value(age, sum_assured):
      row = np.digitize(age, transition_table.index, right=True)
      col = str(sum_assured)
      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'
    

    希望对你有帮助,如果有不清楚的地方写评论。

    【讨论】:

    • 哇@adnanmuttaleb 你是救生员!非常感谢,效果很好!
    • 该表实际上是 csv 文件中较大表的一小部分。我将尝试使用 pandas 输入它,看看我是否可以让它工作。我会告诉你的
    • @Noel 你很受欢迎
    • 你好!所以我尝试了无数次输入数据并使用相同的代码,但它不起作用,我知道这是我忽略的一件小事,但如果你能看看链接 (i.stack.imgur.com/gwD6v.jpg) 指导你到转换表。我需要在代码中添加什么才能使其工作? import pandas as pd data = pd.read_csv("/Users/Noel/Desktop/Transition.csv") 那么你的代码就在这里
    • 嗨@Noel 根据您的问题描述,代码对我来说运行良好,我已经测试了多次。现在,如果有其他或新问题,请打开一个新问题并包含所有必要的详细信息,并就新问题的链接写评论,也许我可以帮助你。
    猜你喜欢
    • 2016-06-05
    • 2018-07-08
    • 2016-09-10
    • 2014-04-17
    • 1970-01-01
    • 1970-01-01
    • 2017-02-06
    • 2013-07-07
    • 2019-08-12
    相关资源
    最近更新 更多